Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

First Order and Second Order Option Greeks in Tradingview Pinescript Code

14 min read

Options payoff curve linked to four sensitivity gauges, option Greeks in TradingView Pine Script

Second order option Greeks such as Vanna, Charm and Vomma measure how the first order Greeks themselves change: how Delta reacts to volatility, how Delta drifts as time passes, and how Vega reacts to volatility. The Pine Script indicator in this post calculates the option premium, implied volatility, all five first order Greeks (Delta, Gamma, Theta, Vega, Rho) and three second order Greeks in real time on any NSE option chart in TradingView, using the Black-Scholes model.

The provided Tradingview Pine Script™ code is an Options Greeks Calculator tailored for use on the TradingView platform. It provides real-time analysis and visualization of First Order and Second Order Option Greeks.

Key takeaways
  • Apply the indicator to an option symbol; it reads the strike, expiry and call/put type from the ticker.
  • Implied volatility is solved from the option’s last price by bisection, then used for every Greek.
  • First order Greeks: Delta, Gamma, Theta, Vega, Rho. Second order option Greeks: Vanna, Charm, Vomma.
  • Theta is per calendar day, Vega per one volatility point; Charm and Rho use yearly and full-unit scales (see the units table).
  • The risk-free rate defaults to 0%; enter a current rate for more accurate Theta and Rho.

List of Option Greeks and Metrics Supported by the Pine Script™ Code

  1. Premium: The current market price of the option contract.
  2. Implied Volatility (IV): The volatility implied by the market price of the option, reflecting the market’s view of the likelihood of changes in the underlying asset’s price.
  3. Delta (Δ): Measures the rate of change of the option’s price with respect to a $1 change in the underlying asset’s price.
  4. Gamma (Γ): Represents the rate of change of Delta with respect to changes in the underlying asset’s price, indicating the curvature of the option’s price curve.
  5. Theta (Θ): Reflects the rate at which the option’s price decays over time, commonly known as time decay.
  6. Vega (V): Measures the sensitivity of the option’s price to a 1% change in the volatility of the underlying asset.
  7. Rho (ρ): Indicates the change in the option’s price resulting from a 1% change in the risk-free interest rate.
  8. Vanna: Captures the sensitivity of Delta to changes in volatility and the sensitivity of Vega to changes in the underlying asset’s price.
  9. Charm: Measures the rate of change of Delta over time, showing how Delta decays as expiration approaches.
  10. Vomma: Represents the rate of change of Vega with respect to changes in volatility, indicating how Vega is expected to change as volatility changes.

These Greeks provide comprehensive insights into the option’s sensitivity to various factors such as underlying price movements, volatility changes, time decay, and interest rate fluctuations, as calculated by the Pine Script™ code.

OpenAlgo Desktop: algo trading on your own computer

WINDOWS, MAC AND LINUX

OpenAlgo Desktop: algo trading on your own computer

Install, sign in, connect your broker and trade. No server to set up and no Python to install.

  • Same API and screens as OpenAlgo web
  • Strategy module, charting and scalping terminals
  • Keys stay encrypted on your machine

First Order vs Second Order Option Greeks

GreekOrderSensitivity ofTo a change inTypical use
DeltaFirstOption priceUnderlying priceDirection exposure, hedge ratio
GammaSecond (of price)DeltaUnderlying priceHow fast Delta changes; risk near expiry
ThetaFirstOption priceTimeDaily time decay
VegaFirstOption priceImplied volatilityVolatility exposure
RhoFirstOption priceInterest rateRate exposure (small for short expiries)
VannaSecondDelta (or Vega)Volatility (or price)How a volatility move shifts your Delta
CharmSecondDeltaTimeDelta drift into expiry, overnight hedging
VommaSecondVegaVolatilityConvexity of volatility exposure

Strictly, Gamma is also a second order Greek (the second derivative of price with respect to the underlying). The indicator groups it with the first order Greeks in its table because traders use it alongside Delta every day.

First Order and Second Order Option Greeks – Tradingview Pinescript Code

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © algostudio

//@version=5
indicator("Options Greeks Calculator - First Order Vs Second Order Greeks", 
         shorttitle="Option Greeks", 
         overlay=false, 
         dynamic_requests = true,
         format=format.price,
         precision=4)

// Constants
var float PI = 3.14159265358979

// Input Parameters
underlyingInput = input.symbol(defval="NSE:NIFTY", title="Underlying Symbol", confirm=true)
riskFreeRate = input.float(defval=0.0, title="Risk Free Rate (%)", group="Option Parameters")/100
dividend = input.float(defval=0.0, title="Dividend Yield (%)", group="Option Parameters")/100

// Plot Selection
plotOptions = input.string("Premium", "Select Plot", options=["Premium", "IV", "Delta", "Gamma", "Theta", "Vega", "Rho", "Vanna", "Charm", "Vomma"], group="Plot Settings", confirm=true)
plotColor = input.color(color.yellow, "Plot Color", group="Plot Settings")
plotThickness = input.int(2, "Plot Thickness", minval=1, maxval=4, group="Plot Settings")

// Expiry time inputs
expiryHour = input.int(15, "Expiry Hour (24h)", minval=0, maxval=23, group="Expiry Settings", confirm=true)
expiryMinute = input.int(30, "Expiry Minute", minval=0, maxval=59, group="Expiry Settings", confirm=true)

// Input Variables for Table Display Settings
tablePosition = input.string(defval = "Top Right", title = "Greeks Table Position", 
  options=["Top Right", "Bottom Right", "Middle Right", "Top Left", "Middle Left"], group="Table Settings")
tableSize = input.string(defval = "Medium", title = "Table Size", 
  options = ["Small", "Large", "Medium"], group="Table Settings")
showTables = input.bool(true, "Show Tables?", group="Table Settings")

// Error Messages
var string ERROR_NOT_OPTION = "Error: Not an option symbol. Please apply this indicator to an option symbol (e.g., NSE:NIFTY24D28P21500)"
var string ERROR_INVALID_FORMAT = "Error: Invalid option symbol format. Expected format: SYMBOL[YYMMDD][C/P]STRIKE"
var string ERROR_MISSING_STRIKE = "Error: Cannot determine strike price from symbol"
var string ERROR_MISSING_EXPIRY = "Error: Cannot determine expiry from symbol"

// Initialize variables with default values
float marketPrice = 0.0
float impliedVolatility = 0.0
float volatility = 0.0
float deltaValue = 0.0
float gammaValue = 0.0
float thetaValue = 0.0
float vegaValue = 0.0
float rhoValue = 0.0
float vannaValue = 0.0
float charmValue = 0.0
float vommaValue = 0.0
float plotValue = 0.0

// Helper function for rounding to 4 decimals
round4(float val) =>
    math.round(val * 10000) / 10000

// Helper function for normal distribution
normDist(z) =>
    b1 = 0.31938153
    b2 = -0.356563782
    b3 = 1.781477937
    b4 = -1.821255978
    b5 = 1.330274429
    p = 0.2316419
    c = 0.39894228

    abs_z = math.abs(z)
    k = 1.0 / (1.0 + p * abs_z)
    
    n = c * math.exp(-z * z / 2.0)
    phi = n * k * (b1 + k * (b2 + k * (b3 + k * (b4 + k * b5))))
    
    z < 0 ? phi : 1.0 - phi

// Option Price calculation function
optionPriceBS(float s, float x, float t, float r, float v, float d, bool isCall) =>
    d1 = (math.log(s/x) + (r - d + math.pow(v, 2)/2) * t) / (v * math.sqrt(t))
    d2 = d1 - v * math.sqrt(t)
    
    float result = 0.0
    if isCall
        result := s * math.exp(-d * t) * normDist(d1) - x * math.exp(-r * t) * normDist(d2)
    else
        result := x * math.exp(-r * t) * normDist(-d2) - s * normDist(-d1) * math.exp(-d * t)
    result

// Calculate Implied Volatility
calculateIV(bool isCall, float s, float x, float t, float r, float mp, float d) =>
    float hval = 3.0
    float lval = 0.0
    float result = 0.0
    
    if isCall
        while (hval - lval > 0.0001)
            mid = (hval + lval) / 2
            theoreticalPrice = optionPriceBS(s, x, t, r, mid, d, isCall)
            if theoreticalPrice > mp
                hval := mid
            else
                lval := mid
    else
        while (hval - lval > 0.0001)
            mid = (hval + lval) / 2
            theoreticalPrice = optionPriceBS(s, x, t, r, mid, d, isCall)
            if theoreticalPrice > mp
                hval := mid
            else
                lval := mid
    
    result := (hval + lval) / 2
    result

// Get spot price from underlying
getSpotPrice() =>
    request.security(underlyingInput, timeframe.period, close)

// Calculate days to expiry
getDaysToExpiry(int expiryYear, int expiryMonth, int expiryDay) =>
    currentTime = time
    expiryTime = timestamp(expiryYear, expiryMonth, expiryDay, expiryHour, expiryMinute)
    float timeToExpiry = (expiryTime - currentTime) / (1000 * 3600 * 24)
    
    float daysRemaining = math.floor(timeToExpiry)
    float hoursRemaining = math.floor((timeToExpiry - daysRemaining) * 24)
    
    [math.max(timeToExpiry, 0.0), daysRemaining, hoursRemaining]

// Symbol parsing function with runtime error
parseOptionSymbol() =>
    bool isCall = false
    float strikePrice = 0.0
    int expYear = 0
    int expMonth = 0
    int expDay = 0
    bool hasError = false
    string errorMsg = ""
    
    symbol = syminfo.ticker
    
    // Remove prefix if present
    if str.contains(symbol, ":")
        symbol := str.substring(symbol, str.pos(symbol, ":") + 1)

    // Find the option type (C or P)
    int optionTypePos = -1
    for i = str.length(symbol) - 1 to 0
        char = str.substring(symbol, i, i + 1)
        if char == "C" or char == "P"
            optionTypePos := i
            break
            
    if optionTypePos == -1
        runtime.error(ERROR_NOT_OPTION)
    
    // Determine option type
    optionType = str.substring(symbol, optionTypePos, optionTypePos + 1)
    isCall := optionType == "C"
    
    // The date should be 6 characters before the option type
    if optionTypePos < 6
        runtime.error(ERROR_INVALID_FORMAT)
        
    dateStart = optionTypePos - 6
    dateStr = str.substring(symbol, dateStart, dateStart + 6)
    
    // Extract strike price (everything after option type)
    strikeStr = str.substring(symbol, optionTypePos + 1)
    
    // Handle strike price
    float strikeNum = str.tonumber(strikeStr)
    if na(strikeNum)
        runtime.error(ERROR_MISSING_STRIKE)
    
    strikePrice := strikeNum
    
    // Parse date components
    if str.length(dateStr) != 6
        runtime.error(ERROR_INVALID_FORMAT)
    
    yearStr = str.substring(dateStr, 0, 2)
    monthStr = str.substring(dateStr, 2, 4)
    dayStr = str.substring(dateStr, 4, 6)
    
    float yearNum = str.tonumber(yearStr)
    float monthNum = str.tonumber(monthStr)
    float dayNum = str.tonumber(dayStr)
    
    if na(yearNum) or na(monthNum) or na(dayNum)
        runtime.error(ERROR_MISSING_EXPIRY)
    
    expYear := 2000 + int(yearNum)
    expMonth := int(monthNum)
    expDay := int(dayNum)
    
    [isCall, strikePrice, expYear, expMonth, expDay, hasError, errorMsg]


// Greeks calculations
delta(float spotPrice, float strikePrice, float annualizedTime, float volatility, bool isCall) =>
    float d1 = (math.log(spotPrice/strikePrice) + (riskFreeRate - dividend + math.pow(volatility, 2)/2) * annualizedTime) / (volatility * math.sqrt(annualizedTime))
    float result = 0.0
    if isCall
        result := normDist(d1)
    else
        result := normDist(d1) - 1
    round4(result)

gamma(float spotPrice, float strikePrice, float annualizedTime, float volatility) =>
    float d1 = (math.log(spotPrice/strikePrice) + (riskFreeRate - dividend + math.pow(volatility, 2)/2) * annualizedTime) / (volatility * math.sqrt(annualizedTime))
    float nd1 = math.exp(-(d1*d1) / 2) / math.sqrt(2 * PI)
    float result = nd1 / (spotPrice * (volatility * math.sqrt(annualizedTime)))
    round4(result)

theta(float spotPrice, float strikePrice, float annualizedTime, float volatility, bool isCall) =>
    float d1 = (math.log(spotPrice/strikePrice) + (riskFreeRate - dividend + math.pow(volatility, 2)/2) * annualizedTime) / (volatility * math.sqrt(annualizedTime))
    float d2 = d1 - volatility * math.sqrt(annualizedTime)
    float nd1 = math.exp(-(d1*d1) / 2) / math.sqrt(2 * PI)
    float nd2 = normDist(d2)

    float theta = 0.0
    if isCall
        theta := - (((spotPrice * volatility * nd1) / (2 * math.sqrt(annualizedTime))) - (riskFreeRate * strikePrice * math.exp(-riskFreeRate * annualizedTime) * nd2))
    else
        theta := - (((spotPrice * volatility * nd1) / (2 * math.sqrt(annualizedTime))) + (riskFreeRate * strikePrice * math.exp(-riskFreeRate * annualizedTime) * (1- nd2)))

    float result = 0.0
    if annualizedTime < float(1) / 365
        result := theta * annualizedTime
    else
        result := theta / 365
    round4(result)

vega(float spotPrice, float strikePrice, float annualizedTime, float volatility) =>
    float d1 = (math.log(spotPrice/strikePrice) + (riskFreeRate - dividend + math.pow(volatility, 2)/2) * annualizedTime) / (volatility * math.sqrt(annualizedTime))
    float nd1 = math.exp(-(d1*d1) / 2) / math.sqrt(2 * PI)
    float vegaOut = 0.01 * spotPrice * math.sqrt(annualizedTime) * nd1  // Changed from result to vegaOut
    round4(vegaOut)

// New First Order Greek - Rho calculation
rho(float spotPrice, float strikePrice, float annualizedTime, float volatility, bool isCall) =>
    float d1 = (math.log(spotPrice/strikePrice) + (riskFreeRate - dividend + math.pow(volatility, 2)/2) * annualizedTime) / (volatility * math.sqrt(annualizedTime))
    float d2 = d1 - volatility * math.sqrt(annualizedTime)
    float result = 0.0
    if isCall
        result := strikePrice * annualizedTime * math.exp(-riskFreeRate * annualizedTime) * normDist(d2)
    else
        result := -strikePrice * annualizedTime * math.exp(-riskFreeRate * annualizedTime) * normDist(-d2)
    round4(result)

// Second Order Greeks calculations
vanna(float spotPrice, float strikePrice, float annualizedTime, float volatility) =>
    float d1 = (math.log(spotPrice/strikePrice) + (riskFreeRate - dividend + math.pow(volatility, 2)/2) * annualizedTime) / (volatility * math.sqrt(annualizedTime))
    float d2 = d1 - volatility * math.sqrt(annualizedTime)
    float nd1 = math.exp(-(d1*d1) / 2) / math.sqrt(2 * PI)
    float result = -nd1 * d2 / volatility
    round4(result)

charm(float spotPrice, float strikePrice, float annualizedTime, float volatility, bool isCall) =>
    float d1 = (math.log(spotPrice/strikePrice) + (riskFreeRate - dividend + math.pow(volatility, 2)/2) * annualizedTime) / (volatility * math.sqrt(annualizedTime))
    float d2 = d1 - volatility * math.sqrt(annualizedTime)
    float nd1 = math.exp(-(d1*d1) / 2) / math.sqrt(2 * PI)
    float result = 0.0
    if isCall
        result := -nd1 * (2*(riskFreeRate-dividend)*annualizedTime - d2*volatility*math.sqrt(annualizedTime))/(2*annualizedTime*volatility*math.sqrt(annualizedTime))
    else
        result := nd1 * (2*(riskFreeRate-dividend)*annualizedTime - d2*volatility*math.sqrt(annualizedTime))/(2*annualizedTime*volatility*math.sqrt(annualizedTime))
    round4(result)

vomma(float spotPrice, float strikePrice, float annualizedTime, float volatility) =>
    float d1 = (math.log(spotPrice/strikePrice) + (riskFreeRate - dividend + math.pow(volatility, 2)/2) * annualizedTime) / (volatility * math.sqrt(annualizedTime))
    float d2 = d1 - volatility * math.sqrt(annualizedTime)
    float tempVega = vega(spotPrice, strikePrice, annualizedTime, volatility)  // Changed from vegaValue to tempVega
    float result = tempVega * d1 * d2 / volatility
    round4(result)

// Function to Get Table Position
gettablePos(pos) =>
    switch pos
        "Top Right" => position.top_right
        "Bottom Right" => position.bottom_right
        "Middle Right" => position.middle_right
        "Top Left" => position.top_left
        "Middle Left" => position.middle_left

// Function to get the Table Size
gettableSize(size) =>
    switch size
        "Small" => size.small
        "Large" => size.large
        "Medium" => size.normal

// Creating Tables with improved styling
var table infoTable = table.new(position.bottom_left, 2, 8,  // Changed from 6 to 8 rows
  border_width=2, 
  border_color=color.gray, 
  frame_color=color.gray, 
  frame_width=2)

var table firstOrderGreeks = table.new(position.top_right, 2, 6,  // Changed from gettablePos(tablePosition)
  border_width=2, 
  border_color=color.gray, 
  frame_color=color.gray, 
  frame_width=2)

var table secondOrderGreeks = table.new(position.bottom_right, 2, 5,  // Keep this at top right
  border_width=2, 
  border_color=color.gray, 
  frame_color=color.gray, 
  frame_width=2)
// Function to plot Info Table
plotInfoTable(table tbl, string tblSize, bool isCall, float strikePrice, float spotPrice, string underlyingInput, float daysRemaining, float hoursRemaining, float premium, float iv) =>
    if showTables
        table.cell(tbl, 0, 0, "Symbol Info", 
          bgcolor=color.black, text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 0, "Value", 
          bgcolor=color.black, text_color=color.white, text_size=tblSize)
        
        table.cell(tbl, 0, 1, "Type", 
          bgcolor=color.rgb(0, 51, 102), text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 1, isCall ? "Call" : "Put", 
          bgcolor=color.black, text_color=color.white, text_size=tblSize)
        
        table.cell(tbl, 0, 2, "Strike", 
          bgcolor=color.rgb(0, 51, 102), text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 2, str.tostring(strikePrice), 
          bgcolor=color.black, text_color=color.white, text_size=tblSize)
        
        table.cell(tbl, 0, 3, "Spot Price", 
          bgcolor=color.rgb(0, 51, 102), text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 3, str.tostring(spotPrice, "#.##"), 
          bgcolor=color.black, text_color=color.white, text_size=tblSize)
        
        table.cell(tbl, 0, 4, "Premium", 
          bgcolor=color.rgb(0, 51, 102), text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 4, str.tostring(premium, "#.##"), 
          bgcolor=color.black, text_color=color.yellow, text_size=tblSize)
        
        table.cell(tbl, 0, 5, "IV %", 
          bgcolor=color.rgb(0, 51, 102), text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 5, str.tostring(iv, "#.##"), 
          bgcolor=color.black, text_color=color.yellow, text_size=tblSize)
        
        table.cell(tbl, 0, 6, "Underlying", 
          bgcolor=color.rgb(0, 51, 102), text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 6, underlyingInput, 
          bgcolor=color.black, text_color=color.white, text_size=tblSize)
        
        table.cell(tbl, 0, 7, "Time to Expiry", 
          bgcolor=color.rgb(0, 51, 102), text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 7, str.tostring(daysRemaining, "#") + "d " + str.tostring(hoursRemaining, "#") + "h", 
          bgcolor=color.black, text_color=color.white, text_size=tblSize)

// Function to plot First Order Greeks Table
plotFirstOrderGreeks(tbl, tblSize) =>
    if showTables
        table.cell(tbl, 0, 0, "First Order Greeks", 
          bgcolor=color.black, text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 0, "Value", 
          bgcolor=color.black, text_color=color.white, text_size=tblSize)
        
        table.cell(tbl, 0, 1, "Delta", 
          bgcolor=color.rgb(0, 51, 0), text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 1, str.tostring(deltaValue, "#.####"), 
          bgcolor=color.black, text_color=color.lime, text_size=tblSize)
        
        table.cell(tbl, 0, 2, "Theta", 
          bgcolor=color.rgb(51, 0, 51), text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 2, str.tostring(thetaValue, "#.####"), 
          bgcolor=color.black, text_color=color.purple, text_size=tblSize)
        
        table.cell(tbl, 0, 3, "Vega", 
          bgcolor=color.rgb(51, 25, 0), text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 3, str.tostring(vegaValue, "#.####"), 
          bgcolor=color.black, text_color=color.orange, text_size=tblSize)
        
        table.cell(tbl, 0, 4, "Rho", 
          bgcolor=color.rgb(0, 25, 51), text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 4, str.tostring(rhoValue, "#.####"), 
          bgcolor=color.black, text_color=color.blue, text_size=tblSize)

// Function to plot Second Order Greeks Table
plotSecondOrderGreeks(tbl, tblSize) =>
    if showTables
        table.cell(tbl, 0, 0, "Second Order Greeks", 
          bgcolor=color.black, text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 0, "Value", 
          bgcolor=color.black, text_color=color.white, text_size=tblSize)
        
        table.cell(tbl, 0, 1, "Gamma", 
          bgcolor=color.rgb(51, 0, 0), text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 1, str.tostring(gammaValue, "#.####"), 
          bgcolor=color.black, text_color=color.red, text_size=tblSize)
        
        table.cell(tbl, 0, 2, "Vanna", 
          bgcolor=color.rgb(51, 25, 51), text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 2, str.tostring(vannaValue, "#.####"), 
          bgcolor=color.black, text_color=color.fuchsia, text_size=tblSize)
        
        table.cell(tbl, 0, 3, "Charm", 
          bgcolor=color.rgb(25, 51, 25), text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 3, str.tostring(charmValue, "#.####"), 
          bgcolor=color.black, text_color=color.green, text_size=tblSize)
        
        table.cell(tbl, 0, 4, "Vomma", 
          bgcolor=color.rgb(51, 51, 25), text_color=color.white, text_size=tblSize)
        table.cell(tbl, 1, 4, str.tostring(vommaValue, "#.####"), 
          bgcolor=color.black, text_color=color.yellow, text_size=tblSize)

// Main calculation block
[isCall, strikePrice, expYear, expMonth, expDay, hasError, errorMsg] = parseOptionSymbol()
spotPrice = getSpotPrice()
[timeToExpiry, daysRemaining, hoursRemaining] = getDaysToExpiry(expYear, expMonth, expDay)
annualizedTime = timeToExpiry/365.0

// Calculate Greeks and update tables
marketPrice := close
impliedVolatility := round4(calculateIV(isCall, spotPrice, strikePrice, annualizedTime, riskFreeRate, marketPrice, dividend) * 100)
volatility := impliedVolatility/100
deltaValue := delta(spotPrice, strikePrice, annualizedTime, volatility, isCall)
gammaValue := gamma(spotPrice, strikePrice, annualizedTime, volatility)
thetaValue := theta(spotPrice, strikePrice, annualizedTime, volatility, isCall)
vegaValue := vega(spotPrice, strikePrice, annualizedTime, volatility)
rhoValue := rho(spotPrice, strikePrice, annualizedTime, volatility, isCall)
vannaValue := vanna(spotPrice, strikePrice, annualizedTime, volatility)
charmValue := charm(spotPrice, strikePrice, annualizedTime, volatility, isCall)
vommaValue := vomma(spotPrice, strikePrice, annualizedTime, volatility)

// Calculate plot value
plotValue := switch plotOptions
    "Premium" => marketPrice
    "IV" => impliedVolatility
    "Delta" => deltaValue
    "Gamma" => gammaValue
    "Theta" => thetaValue
    "Vega" => vegaValue
    "Rho" => rhoValue
    "Vanna" => vannaValue
    "Charm" => charmValue
    "Vomma" => vommaValue
    => marketPrice  // default case

// Update tables
if barstate.islast and not hasError
    plotInfoTable(infoTable, gettableSize(tableSize), isCall, strikePrice, spotPrice, underlyingInput, daysRemaining, hoursRemaining, marketPrice, impliedVolatility)
    plotFirstOrderGreeks(firstOrderGreeks, gettableSize(tableSize))
    plotSecondOrderGreeks(secondOrderGreeks, gettableSize(tableSize))

// Main plot
plot(plotValue, color=plotColor, linewidth=plotThickness)

Key Components of the Code

  1. Input Parameters:
    • Underlying Symbol: The asset on which the option is based.
    • Risk-Free Rate: The annual risk-free interest rate used in calculations.
    • Dividend Yield: The annual dividend yield of the underlying asset (set to zero in this case).
    • Plot Settings: Options to select which Greek or parameter to plot, along with customization of colors and thickness.
    • Expiry Settings: Inputs for specifying the expiration date and time of the option.
    • Table Settings: Configurations for displaying information tables on the chart.
  2. Symbol Parsing:
    • The code parses the option’s ticker symbol to extract whether it’s a call or put, the strike price, and the expiration date.
    • It handles errors gracefully, providing informative messages if the symbol format is incorrect.
  3. Market Data Retrieval:
    • Spot Price: Obtains the current price of the underlying asset.
    • Time to Expiry: Calculates the remaining time until the option expires, expressed in years for the formulas.
  4. Calculations:
    • Option Price: Uses the Black-Scholes formula to calculate the theoretical price of the option.
    • Implied Volatility: Determines the implied volatility by finding the volatility input that makes the theoretical price equal to the market price.
    • First Order Greeks: Computes Delta, Gamma, Theta, Vega, and Rho using the standard formulas.
    • Second Order Greeks: Calculates Vanna, Charm, and Vomma to assess higher-order sensitivities.
  5. Visualization:
    • Plotting: Allows the user to plot any of the calculated Greeks or the option’s premium directly on the chart.
    • Tables: Displays detailed information about the option and its Greeks in tables positioned on the chart for easy reference.
  6. User Interaction and Customization:
    • Users can customize various aspects such as the plot color, thickness, table position, and size.
    • The code adapts to the user’s inputs, recalculating and updating the display in real-time.

How the Code Works

Initialization:

  • Sets up constants and variables.
  • Defines helper functions for calculations and formatting.

Data Processing:

  • Parses the option symbol to extract necessary details.
  • Retrieves the spot price and calculates time to expiry.

Calculations:

  • Computes the theoretical option price and implied volatility.
  • Calculates each Greek using the appropriate mathematical formulas.

Output Generation:

  • Updates the tables with the latest calculations.
  • Plots the selected Greek or parameter on the chart.

Error Handling:

  • Includes checks to ensure that the calculations are only performed when the necessary data is available and valid.
  • Provides error messages to guide the user if there’s an issue with the input data.

Units used in the code

OutputFormula in the scriptUnit
ThetaBlack-Scholes theta divided by 365Premium change per calendar day
Vega0.01 x S x sqrt(T) x N'(d1)Premium change per 1 point of IV
RhoK x T x e^(-rT) x N(d2) for callsPer 1.00 (100 percentage points) change in rate; divide by 100 for a 1% change
Vanna-N'(d1) x d2 / sigmaDelta change per 1.00 change in volatility; divide by 100 per IV point
CharmBlack-Scholes charm with time in yearsDelta change per year; divide by 365 for per day
VommaVega x d1 x d2 / sigmaVega change for a change in volatility

The post’s list above describes Rho per 1% change in rates; the script’s Rho value is per full unit, so divide it by 100 to read it that way. Time to expiry is measured in calendar days from the current bar to the expiry date and time you set (default 15:30).

How to Use the Option Greeks Indicator on TradingView

  1. Open the chart of an NSE option contract (not the index or futures). The script parses the ticker as SYMBOL + YYMMDD + C or P + STRIKE and stops with an error message if it cannot.
  2. Add the indicator from the Pine Editor and set Underlying Symbol (default NSE:NIFTY).
  3. Set the Risk Free Rate and Dividend Yield. Both default to 0%.
  4. Check the expiry hour and minute (default 15:30, the NSE close).
  5. Choose what to plot (Premium, IV, Delta, Gamma, Theta, Vega, Rho, Vanna, Charm or Vomma) and where to show the tables.

Worked Example: Reading Second Order Option Greeks

To get a feel for the numbers, here are values from the same Black-Scholes formulas for a Nifty call with 7 calendar days to expiry, spot 25,000, IV 12% and a 0% rate (illustrative, not market quotes):

GreekATM call (25,000 strike)OTM call (25,300 strike)
Premium165.7457.93
Delta0.5030.239
Theta per day-11.84-9.20
Vega per IV point13.8110.74
Vanna (per IV point)0.00030.0188
Charm (per day)-0.0002-0.0161
Vomma-0.00846.10

Read it like this. At the money, Vanna and Charm are close to zero: Delta stays near 0.5 whatever happens to time or volatility. Out of the money, the picture changes. Each day that passes with spot unchanged cuts Delta by about 0.016 (Charm), while a one point rise in IV adds about 0.019 to Delta (Vanna). Large Vomma on the OTM option shows its Vega itself grows quickly when volatility rises, which is why OTM options can reprice sharply on volatility spikes.

Limitations to Keep in Mind

  • Black-Scholes assumes constant volatility and European exercise; real option prices show skew, so each strike has its own IV.
  • IV is solved from the option’s last traded price. On illiquid strikes, a stale last price gives a misleading IV and Greeks.
  • The normal distribution uses a polynomial approximation, which is accurate enough for trading but not exact.
  • Calendar-day time to expiry overstates decay over weekends compared with trading-day models.

The script is written in Pine Script v5. It runs as is; if you want to upgrade it, TradingView’s Pine Editor has a “Convert code to v6” option since Pine Script v6 was released in December 2024 (TradingView blog).

Understanding the Greeks is essential for anyone involved in options trading, as they provide valuable insights into the risks and potential movements of option prices. The Pine Script™ code discussed in this blog post offers a practical tool for calculating and visualizing both First Order and Second Order Greeks directly within the TradingView platform.

By integrating these calculations into your trading workflow, you can make more informed decisions, better manage risk, and enhance your overall trading strategy. Whether you’re a seasoned trader or just starting, using tools like this can significantly improve your understanding and execution in the options market.

Related reading: a simpler real-time option Greeks indicator with implied volatility in Pine Script, computing option Greeks using OpenAlgo and Mibian in Python, the realtime option Greeks module for Amibroker, and the difference between India VIX and implied volatility.

Frequently Asked Questions

What are second order option Greeks?

They measure how first order Greeks change. Vanna is the change in Delta for a change in volatility, Charm is the change in Delta over time, and Vomma is the change in Vega for a change in volatility. Gamma is also a second order Greek of price.

Why is Charm important for option sellers?

Charm shows how Delta drifts as expiry approaches even if spot does not move. Out-of-the-money options lose Delta quickly near expiry, which changes your hedge requirement overnight.

Can TradingView calculate option Greeks?

Yes, with a Pine Script indicator like this one. It reads the option and underlying prices, solves implied volatility and computes the Greeks using Black-Scholes on every bar.

What risk-free rate should I use for Indian options?

A short-term government rate such as the current 91-day Treasury bill yield is a common choice. For weekly expiries the impact on Delta and Gamma is small, but it affects Rho and Theta.

Marketcalls Elite Traders Club

MEMBERSHIP

Marketcalls Elite Traders Club

Every Marketcalls course and live mentorship in one membership: 127 courses and 2,500+ hours of learning.

  • Market Profile, Orderflow, AFL, Pine Script and Python
  • Live mentorship and TradEdge trading room
  • Premium tools and the Elite Slack community

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More