/VX Expiration Close and /VX Expiration Open

baTrader

New member
Plus
I've been working on this for weeks, but am not able to generate a solution and not seeing anything online. I need to get the last candle close of the back month /VX expiration and the first candle open of the current month /VX expiration. Any help would be GREATLY appreciated. Code that I'm currently working based on: https://usethinkscript.com/threads/vx-futures-contango-indicator-for-thinkorswim.1177/
and image attached.
VX_Chart.jpg

Code:
# VX Futures Contango
# tomsk
# 12.8.2019

# V1.0 - 11.28.2019 - thelonelytrader - Initial version of posted study
# V2.0 - 12.08.2019 - tomsk           - Major revamped version to handle /VX taxonomy

# Displays Contango relationship between the Front and Back Month /VX futures
#
# According to the design from the original author, there are three possible
# input flavors. It is set to default to option #3, for contango % thresholds
#     1 For relative cumulative difference with respect to Front month
#     2 For absolute difference.
#     3 For Contango % thresholds, from (BM-FM)*100/FM.
# https://usethinkscript.com/threads/vx-futures-contango-indicator-for-thinkorswim.1177/#post-11256
# tomsk post #5
# Modified 7/30/2025 Frank Galan - Need to get first bar close of back monthe /VX expiration and current month /VX expiration open

declare lower;
declare hide_on_intraday;

input showBubbles = no;
input showDebug = no;
input showDebug2 = no;
input showLabel = no;
input Threshold_shortVol = 6.77;
input Threshold_longVol = 2.90;
input flavor = 3;

# Below flags the date for expiring Front Month /VX futures per CBOE specs
# Note: Regarding the Holidays, only one occurrence since 2010, which is
# hard coded in line below. For some unknown reason, TOS does not respond
# to daily /VX futures per specification before August 2010, so data seems
# valid after Aug 2010
#
# In debugging observed TOS sometimes misses complete trading days, the
# "/VX" reference in TOS does not match the CBOE spec for settlement and
# TOS "opportunities" seem to be dynamic (not static bugs). TOS inferred no
# trading of "/VX" between 7/16/2013 and 7/22/2016. (Missing 3 trading days)

script VXexp {
    def date = GetYYYYMMDD();
    def isholiday = date == 20140319; # Manual injection of holiday on 4/18/14 which alters VX settlement date in March.
    def n3rdfa = Next3rdFriday(1);
    def n3rdfb = Next3rdFriday(2);
    def n3rdf = if (n3rdfa < 4) then n3rdfb else n3rdfa; # Pick Next month's expiration, not this month.
    plot VXexp = if (isholiday) then 1 else ((n3rdf == 30) and !isholiday[1]);#and (dow == 3);
}

script LsD {
    input date = 2010;
    plot LsD = date - 2000;
}

def date = GetYYYYMMDD();
def dom = GetDayOfMonth(date);
def newmo = dom < dom[1];
def incmo = if newmo then 0 else if VXexp() then 1 else incmo[1];
def Y_ = GetYear();
def Y = LsD(Y_);
def MM = GetMonth();

def fm = if (MM + incmo) > 12 then 1 else (MM + incmo);
def fmchange = fm != fm[1];
def fmY = if fmchange then (if (MM + incmo) > 12 then LsD(Y + 1) else Y) else fmY[1];
def bm = if (fm + 1) > 12 then 1 else if (fm - 1) < 0 then 12 else (fm-1);
def bmY = if fmchange then (if (bm < 3) then LsD(Y_ + 1) else Y) else bmY[1];

#AddLabel(1, "/VX Contango Relationship", Color.YELLOW);
AddLabel(showDebug, "Back Month Symbol = " + ((if bm == 1  then "/VXF" else
                                               if bm == 2  then "/VXG" else
                                               if bm == 3  then "/VXH" else
                                               if bm == 4  then "/VXJ" else
                                               if bm == 5  then "/VXK" else
                                               if bm == 6  then "/VXM" else
                                               if bm == 7  then "/VXN" else
                                               if bm == 8  then "/VXQ" else
                                               if bm == 9  then "/VXU" else
                                               if bm == 10 then "/VXV" else
                                               if bm == 11 then "/VXX" else
                                               if bm == 12 then "/VXZ" else " ") + bmY), Color.PINK);

AddLabel(showDebug, "Front Month Symbol = " + ((if fm == 1  then "/VXF" else
                                               if fm == 2  then "/VXG" else
                                               if fm == 3  then "/VXH" else
                                               if fm == 4  then "/VXJ" else
                                               if fm == 5  then "/VXK" else
                                               if fm == 6  then "/VXM" else
                                               if fm == 7  then "/VXN" else
                                               if fm == 8  then "/VXQ" else
                                               if fm == 9  then "/VXU" else
                                               if fm == 10 then "/VXV" else
                                               if fm == 11 then "/VXX" else
                                               if fm == 12 then "/VXZ" else " ") + fmY), Color.PINK);

def fmp = open(symbol = (if fm == 1  then "/VXF" else
                 if fm == 2  then "/VXG" else
                 if fm == 3  then "/VXH" else
                 if fm == 4  then "/VXJ" else
                 if fm == 5  then "/VXK" else
                 if fm == 6  then "/VXM" else
                 if fm == 7  then "/VXN" else
                 if fm == 8  then "/VXQ" else
                 if fm == 9  then "/VXU" else
                 if fm == 10 then "/VXV" else
                 if fm == 11 then "/VXX" else
                 if fm == 12 then "/VXZ" else " ") + bmY);

def bmp = close(symbol = (if bm == 1  then "/VXF" else
                 if bm == 2  then "/VXG" else
                 if bm == 3  then "/VXH" else
                 if bm == 4  then "/VXJ" else
                 if bm == 5  then "/VXK" else
                 if bm == 6  then "/VXM" else
                 if bm == 7  then "/VXN" else
                 if bm == 8  then "/VXQ" else
                 if bm == 9  then "/VXU" else
                 if bm == 10 then "/VXV" else
                 if bm == 11 then "/VXX" else
                 if bm == 12 then "/VXZ" else " ") + bmY);

AddLabel(showDebug, "fm = " + fm, Color.YELLOW);
AddLabel(showDebug, "bm = " + bm, Color.YELLOW);
AddLabel(showDebug, "fmp = " + fmp, Color.YELLOW);
AddLabel(showDebug, "bmp = " + bmp, Color.YELLOW);
AddLabel(showDebug, "MM = " + MM, Color.YELLOW);
AddLabel(showDebug, "Y_ = " + Y_, Color.YELLOW);
AddLabel(showDebug, "Y = " + Y, Color.YELLOW);
AddLabel(showDebug, "bmY = " + bmY, Color.YELLOW);

# TOS may miss some vx futures quotes, so if this occurs re-use the prior
# day close for the missing entry. The filter below accomplishes this.

def fmpfiltered = if IsNaN(fmp) then  fmpfiltered[1]  else fmp;
def bmpfiltered = if IsNaN(bmp) then  bmpfiltered[1]  else bmp;
def reladj = if (bmpfiltered > 0) then bmpfiltered else 1;

AddLabel(showDebug, "fmpfiltered = " + fmpfiltered, Color.Yellow);
AddLabel(showDebug, "bmpfiltered = " + bmpfiltered, Color.Yellow);

# def fmpfiltered = if isnan(fmp) then if (fmpfiltered[1]>0) then fmpfiltered[1] else double.nan  else fmp;
# def bmpfiltered = if isnan(bmp) then if (bmpfiltered[1]>0) then  bmpfiltered[1] else double.nan else bmp;

def AbsDiffContango = if (BarNumber() < 5)
                      then 0
                      else (if (flavor == 1)
                            then (bmpfiltered - fmpfiltered) / reladj
                            else (bmpfiltered - fmpfiltered));
def ContangoBias = if (BarNumber() < 5)
                   then 0
                   else ContangoBias[1] + (if (flavor == 1)
                                           then (bmpfiltered - fmpfiltered) / reladj
                                           else (bmpfiltered - fmpfiltered));
plot FmBmContango = if IsNaN(fmp) then Double.NaN
                    else if (flavor == 2)
                         then AbsDiffContango
                    else if (flavor == 3)
                         then Double.NaN
                         else ContangoBias;
FmBmContango.DefineColor("green", Color.GREEN);
FmBmContango.DefineColor("red", Color.RED);
FmBmContango.DefineColor("white", Color.WHITE);

def ContangoPerCentage = 100 * AbsDiffContango / fmpfiltered;

AddLabel(showDebug2, "AbsDiffContango = " + AbsDiffContango, Color.YELLOW);
AddLabel(showDebug2, "ContangoBias = " + ContangoBias, Color.YELLOW);
AddLabel(showDebug2, "FmBmContango = " + FmBmContango, Color.YELLOW);
AddLabel(showDebug2, "ContangoPerCentage = " + ContangoPerCentage, Color.YELLOW);

plot Cper = if ((flavor == 3) and  (IsNaN(fmp) == 0)) then ContangoPerCentage else Double.NaN;
Cper.DefineColor("Green", Color.GREEN);
Cper.DefineColor("Red", Color.RED);
Cper.DefineColor("White", Color.WHITE);
Cper.AssignValueColor(if (ContangoPerCentage > Threshold_shortVol) then Cper.Color("Green")
                      else if (ContangoPerCentage > Threshold_longVol) then Cper.Color("White")
                      else Cper.Color("Red"));
Cper.SetPaintingStrategy(PaintingStrategy.POINTS);

def Direction = ContangoBias > ContangoBias[1];
def DirectionChanges = if (BarNumber() == 1) then 0
                       else if (Direction != Direction[1]) then DirectionChanges[1] + 1
                       else DirectionChanges[1];
FmBmContango.AssignValueColor(if (ContangoBias > ContangoBias[1]) then FmBmContango.Color("Green")
                              else if (ContangoBias == ContangoBias[1]) then FmBmContango.Color("White")
                              else FmBmContango.Color("Red"));
FmBmContango.SetPaintingStrategy(PaintingStrategy.POINTS);

def InContango = if ((BarNumber() == 1) or (DirectionChanges < 1)) then 0 else InContango[1] + (bmpfiltered > fmpfiltered);
def NotContango = if ((BarNumber() == 1) or (DirectionChanges < 1)) then 0 else NotContango[1] + (bmpfiltered <= fmpfiltered);

plot UpperThreshold = if (flavor == 3) then Threshold_shortVol else Double.NaN;
plot LowerThreshold = if (flavor == 3) then Threshold_longVol else Double.NaN;

AddChartBubble(showBubbles and Direction and !Direction[1], ContangoBias, DirectionChanges, Color.GRAY, 1);
AddChartBubble(showBubbles and !Direction and Direction[1], ContangoBias, DirectionChanges, Color.YELLOW, 0);
AddVerticalLine(VXexp(), "/VX Expiration", Color.WHITE);
# End VX Futures Contango
 
Last edited by a moderator:
Solution
Ah, small typo in the offset. I think I broke it a little trying to avoid always showing a rollover on the chart's final bar. Change the Exp variable to what is shown below. It will line up with hasContractChangeEvent() this way.

Code:
def Exp =
    isNaN(CC[-1])
    && !isNaN(CC)
    && !isNaN(close[-1]);

Just a side note, enabling extended hours does effect Daily futures charts. It is already considered to be tomorrow's pre-market after maintenance, which is usually at 6:00 PM today depending on the contract.

When charting specific contracts, as opposed to the continuous contract, you may end up with an extra daily bar representing that time period. This will extend beyond the actual calendar date of expiration.
I'll work on it more later... this should at least get rid of holiday checking and all that.
Work in progess

Code:
def CC =
 Close(
    "/VX" +
    (    if GetMonth() == 01 then "F"
    else if GetMonth() == 02 then "G"
    else if GetMonth() == 03 then "H"
    else if GetMonth() == 04 then "J"
    else if GetMonth() == 05 then "K"
    else if GetMonth() == 06 then "M"
    else if GetMonth() == 07 then "N"
    else if GetMonth() == 08 then "Q"
    else if GetMonth() == 09 then "U"
    else if GetMonth() == 10 then "V"
    else if GetMonth() == 11 then "X"
    else if GetMonth() == 12 then "Z"
    else "")
    + (Floor(GetYear() % 100)  
 )
);
def Exp =
    isNaN(CC) && !isNaN(CC[1]);
AddVerticalLine(
    Exp, GetYYYYMMDD(), color.white);
 
Last edited:
8enk9dz.png


Code:
#January    F
#February   G
#March      H
#April      J
#May        K
#June       M
#July       N
#August     Q
#September  U
#October    V
#November   X
#December   Z

def Year =
    Floor(GetYear() % 100);
def CC =
 Close(
    "/VX" +
    (    if GetMonth() == 01 then "F"
    else if GetMonth() == 02 then "G"
    else if GetMonth() == 03 then "H"
    else if GetMonth() == 04 then "J"
    else if GetMonth() == 05 then "K"
    else if GetMonth() == 06 then "M"
    else if GetMonth() == 07 then "N"
    else if GetMonth() == 08 then "Q"
    else if GetMonth() == 09 then "U"
    else if GetMonth() == 10 then "V"
    else if GetMonth() == 11 then "X"
    else if GetMonth() == 12 then "Z"
    else "") + Year  
);
def NC =
 Open(
    "/VX" +
    (    if GetMonth() == 12 then "F"
    else if GetMonth() == 01 then "G"
    else if GetMonth() == 02 then "H"
    else if GetMonth() == 03 then "J"
    else if GetMonth() == 04 then "K"
    else if GetMonth() == 05 then "M"
    else if GetMonth() == 06 then "N"
    else if GetMonth() == 07 then "Q"
    else if GetMonth() == 08 then "U"
    else if GetMonth() == 09 then "V"
    else if GetMonth() == 10 then "X"
    else if GetMonth() == 11 then "Z"
    else "") + (Year + (GetMonth()==12))
);
def Exp =
    isNaN(CC) && !isNaN(CC[1]);
def xPrice =
    CC[1];
def nPrice =
    NC;
AddVerticalLine(
    Exp, "", color.white);
addchartBubble(Exp,high,
    "Exp Close: " + xPrice + "\nNext Open: " + nPrice
,color.white);
 
Thanks! This solves part of the problem and tightens up the code quite a bit. The values in the bubble are shifted right one candle. I'm not seeing how to get the right values. Any additional help will be greatly appreciated! Image Attached.

It seems the white vertical line is not at the expiration.
 

Attachments

  • VX_Chart2.jpg
    VX_Chart2.jpg
    131.6 KB · Views: 172
Ah, small typo in the offset. I think I broke it a little trying to avoid always showing a rollover on the chart's final bar. Change the Exp variable to what is shown below. It will line up with hasContractChangeEvent() this way.

Code:
def Exp =
    isNaN(CC[-1])
    && !isNaN(CC)
    && !isNaN(close[-1]);

Just a side note, enabling extended hours does effect Daily futures charts. It is already considered to be tomorrow's pre-market after maintenance, which is usually at 6:00 PM today depending on the contract.

When charting specific contracts, as opposed to the continuous contract, you may end up with an extra daily bar representing that time period. This will extend beyond the actual calendar date of expiration.
 
Solution
Thanks Joshua. Looking Good now. I'll just need to keep an eye on it for several expirations, but this looks like the solution!
Ah, small typo in the offset. I think I broke it a little trying to avoid always showing a rollover on the chart's final bar. Change the Exp variable to what is shown below. It will line up with hasContractChangeEvent() this way.

Code:
def Exp =
    isNaN(CC[-1])
    && !isNaN(CC)
    && !isNaN(close[-1]);

Just a side note, enabling extended hours does effect Daily futures charts. It is already considered to be tomorrow's pre-market after maintenance, which is usually at 6:00 PM today depending on the contract.

When charting specific contracts, as opposed to the continuous contract, you may end up with an extra daily bar representing that time period. This will extend beyond the actual calendar date of expiration.
 
Ok. I've run into this situation before, I need to retrieve the values from the above study to create a label. I've researched it and researched it many times and still have no idea how to solve this. If someone can help me with this, again, I'd greatly appreciate the help.

I've tried the following. I haven't used fold in TOS before. It doesn't appear to like the fold statement:

Code:
def inc = fold n = -45 to 0 while lastExp == 0 do lastExp = isNAN(CC[n-1]) && !isNaN(CC[n]) & !isNaN(close[n-1]);
def lastXPrice = CC[inc+1];
def lastNPrice = NC[inc];
 
Describe what you're trying to do in plain English.
Sure. Thanks.
I need to retrieve the values that correspond to the latest expiration close, and expiration open, to be able to display them in a label. With the current code, I see the values displayed in the bubble, but am struggling how to get them to display in a label after expiration has passed. Hope this helps.

I'm including the current TEST code which is not working.

Code:
# Label to show whether current /VX is GT /VX exp close + /VX_Close Day 1 Open
# Frank Galan 9/5/2025

# Solution by Joshua:
# https://usethinkscript.com/threads/vx-expiration-close-and-vx-expiration-open.21349/

#January    F
#February   G
#March      H
#April      J
#May        K
#June       M
#July       N
#August     Q
#September  U
#October    V
#November   X
#December   Z

declare upper;

def n = hasContractChangeEvent();

def Year =
    Floor(GetYear() % 100);
def CC =
 Close(
    "/VX" +
    (    if GetMonth() == 01 then "F"
    else if GetMonth() == 02 then "G"
    else if GetMonth() == 03 then "H"
    else if GetMonth() == 04 then "J"
    else if GetMonth() == 05 then "K"
    else if GetMonth() == 06 then "M"
    else if GetMonth() == 07 then "N"
    else if GetMonth() == 08 then "Q"
    else if GetMonth() == 09 then "U"
    else if GetMonth() == 10 then "V"
    else if GetMonth() == 11 then "X"
    else if GetMonth() == 12 then "Z"
    else "") + Year
);
def NC =
 Open(
    "/VX" +
    (    if GetMonth() == 12 then "F"
    else if GetMonth() == 01 then "G"
    else if GetMonth() == 02 then "H"
    else if GetMonth() == 03 then "J"
    else if GetMonth() == 04 then "K"
    else if GetMonth() == 05 then "M"
    else if GetMonth() == 06 then "N"
    else if GetMonth() == 07 then "Q"
    else if GetMonth() == 08 then "U"
    else if GetMonth() == 09 then "V"
    else if GetMonth() == 10 then "X"
    else if GetMonth() == 11 then "Z"
    else "") + (Year + (GetMonth()==12))
);
def Exp =
    isNaN(CC[-1])
    && !isNaN(CC)
    && !isNaN(close[-1]);
def xPrice =
    CC[1];
def nPrice =
    NC;

# Theoretically count from 45 days back (ensures prior to last expiration) to the most recent expiration to try to get the values
# Thinkscript doesn't like the fold statement.  I'm unsure how to proceed
def inc = fold n = -45 to 0 while lastExp == 0 do lastExp = isNAN(CC[n-1]) && !isNaN(CC[n]) & !isNaN(close[n-1]);
def lastXPrice = CC[inc + 1];
def lastXPrice = NC[inc];
def midVX_Exp = Round((lastXPrice + lastXPrice) / 2, 2);
def VX_Value = if IsNaN(close(symbol = "/VX")) then close(symbol = "/VX")[1] else close(symbol = "/VX");

AddLabel(yes, "Exp: " + Exp + " x: " + lastXPrice + "n: " + lastXPrice + " VX mid: " + midVX_Exp + " VX: " + VX_Value, if VX_Value >= midVX_Exp then Color.RED else Color.GREEN);
 
Last edited:
Just labels eh? They're always going to be based on the final bar, so you can just carry the values forward rather than searching backwards for them.

Code:
#January    F
#February   G
#March      H
#April      J
#May        K
#June       M
#July       N
#August     Q
#September  U
#October    V
#November   X
#December   Z

input FontSize = FontSize.MEDIUM;
input Location = Location.TOP_LEFT;
defineglobalColor("Cur",color.white);
defineglobalColor("Pri",color.white);

def Year =
    Floor(GetYear() % 100);
def CC =
 Close(
    "/VX" +
    (    if GetMonth() == 01 then "F"
    else if GetMonth() == 02 then "G"
    else if GetMonth() == 03 then "H"
    else if GetMonth() == 04 then "J"
    else if GetMonth() == 05 then "K"
    else if GetMonth() == 06 then "M"
    else if GetMonth() == 07 then "N"
    else if GetMonth() == 08 then "Q"
    else if GetMonth() == 09 then "U"
    else if GetMonth() == 10 then "V"
    else if GetMonth() == 11 then "X"
    else if GetMonth() == 12 then "Z"
    else "") + Year 
);
def NC =
 Open(
    "/VX" +
    (    if GetMonth() == 12 then "F"
    else if GetMonth() == 01 then "G"
    else if GetMonth() == 02 then "H"
    else if GetMonth() == 03 then "J"
    else if GetMonth() == 04 then "K"
    else if GetMonth() == 05 then "M"
    else if GetMonth() == 06 then "N"
    else if GetMonth() == 07 then "Q"
    else if GetMonth() == 08 then "U"
    else if GetMonth() == 09 then "V"
    else if GetMonth() == 10 then "X"
    else if GetMonth() == 11 then "Z"
    else "") + (Year + (GetMonth()==12))
);
def Exp =
    isNaN(CC[-1])
    && !isNaN(CC)
    && !isNaN(close[-1]);
def xPrice =
    CC[1];
def nPrice =
    NC;
def Cur =
    if (Exp,nPrice,Cur[1]);
def Pri =
    if (Exp,xPrice,Pri[1]);
def Dif =
    Cur - Pri;
#plot x = cur; x.setpaintingStrategy(12);
#plot iHateThisColor = double.nan;
#plot y = pri; y.setpaintingStrategy(12);
AddLabel(yes," Current: " + astext(Cur) + " ",GlobalColor("cur"),Location,FontSize);
AddLabel(yes," Prior: " + astext(Pri) + " ",GlobalColor("pri"),Location,FontSize);
AddLabel(yes," Difference: " + astext(Dif) + " ",
    if Dif > 0 then color.light_green
    else if !dif then color.yellow
    else color.orange
,Location,FontSize);
AddVerticalLine(
    Exp, "", color.white);
addchartBubble(Exp,high,
    "Exp Close: " + xPrice + "\nNext Open: " + nPrice
,color.white);
 
@Joshua

Unfortunately, the /VX expiration close and open don't appear on the chart on the date of expiration, but do on the following day. I've been waiting to test this scenario. Is there a way to adjust this so it appears at expiration? I've been trying to understand how the code works, but not having any luck. Thx.
VX at Exp No Bubble.png

Code:
# https://usethinkscript.com/threads/vx-expiration-close-and-vx-expiration-open.21349/

# Solution by Joshua:
# https://usethinkscript.com/threads/vx-expiration-close-and-vx-expiration-open.21349/

#January    F
#February   G
#March      H
#April      J
#May        K
#June       M
#July       N
#August     Q
#September  U
#October    V
#November   X
#December   Z

def Year =
    Floor(GetYear() % 100);
def CC =
 Close(
    "/VX" +
    (    if GetMonth() == 01 then "F"
    else if GetMonth() == 02 then "G"
    else if GetMonth() == 03 then "H"
    else if GetMonth() == 04 then "J"
    else if GetMonth() == 05 then "K"
    else if GetMonth() == 06 then "M"
    else if GetMonth() == 07 then "N"
    else if GetMonth() == 08 then "Q"
    else if GetMonth() == 09 then "U"
    else if GetMonth() == 10 then "V"
    else if GetMonth() == 11 then "X"
    else if GetMonth() == 12 then "Z"
    else "") + Year
);
def NC =
 Open(
    "/VX" +
    (    if GetMonth() == 12 then "F"
    else if GetMonth() == 01 then "G"
    else if GetMonth() == 02 then "H"
    else if GetMonth() == 03 then "J"
    else if GetMonth() == 04 then "K"
    else if GetMonth() == 05 then "M"
    else if GetMonth() == 06 then "N"
    else if GetMonth() == 07 then "Q"
    else if GetMonth() == 08 then "U"
    else if GetMonth() == 09 then "V"
    else if GetMonth() == 10 then "X"
    else if GetMonth() == 11 then "Z"
    else "") + (Year + (GetMonth()==12))
);
def Exp =
    isNaN(CC[-1])
    && !isNaN(CC)
    && !isNaN(close[-1]);
def xPrice =
    CC[1];
def nPrice =
    NC;
AddVerticalLine(
    Exp, "", color.white);
addchartBubble(Exp,high,
    "Exp Close: " + xPrice + "\nMid: " + (xPrice+nPrice)/2 +"\nNext Open: " + nPrice
,color.white);
 
Last edited by a moderator:
I'm not following. Manually determine what it should be saying, and tell me, versus what it is saying. Or draw a mockup of what you want to see over the screen shot, or something like that. Again, the fix is probably very easy coding wise, I just don't understand exactly what you want.
 
I'm not following. Manually determine what it should be saying, and tell me, versus what it is saying. Or draw a mockup of what you want to see over the screen shot, or something like that. Again, the fix is probably very easy coding wise, I just don't understand exactly what you want.
The bubble, on the day of expiration is missing. I've added it in a mockup as suggested. Currently the bubble does not appear until the second day after expiration.
VX at Exp No Bubble Expected.png
 
On day 1 of Expiration what I have currently is no bubble (first Image).
What I'm looking for on day 1 of expiration and forward is the bubble (second image).

Currently the bubble appears, but only on day 2 and forward until the next expiration.

I hope this helps.

Thank you.
Code:
# https://usethinkscript.com/threads/vx-expiration-close-and-vx-expiration-open.21349/

# Solution by Joshua:
# https://usethinkscript.com/threads/vx-expiration-close-and-vx-expiration-open.21349/

#January    F
#February   G
#March      H
#April      J
#May        K
#June       M
#July       N
#August     Q
#September  U
#October    V
#November   X
#December   Z

#declare hide_on_intraday;

input FontSize = FontSize.SMALL;
input Location = Location.TOP_LEFT;

DefineGlobalColor("Cur", Color.WHITE);
DefineGlobalColor("Pri", Color.WHITE);

def agg = GetAggregationPeriod();
def p = AggregationPeriod.DAY;
def aggDaily = if agg == p then 1 else 0;
#AddLabel(yes, "agg " + agg, Color.WHITE);
#AddLabel(yes, "p " + p, Color.WHITE);


def Year =
    Floor(GetYear() % 100);

def CC = close(period = p, symbol = "/VX" +
    (    if GetMonth() == 01 then "F"
    else if GetMonth() == 02 then "G"
    else if GetMonth() == 03 then "H"
    else if GetMonth() == 04 then "J"
    else if GetMonth() == 05 then "K"
    else if GetMonth() == 06 then "M"
    else if GetMonth() == 07 then "N"
    else if GetMonth() == 08 then "Q"
    else if GetMonth() == 09 then "U"
    else if GetMonth() == 10 then "V"
    else if GetMonth() == 11 then "X"
    else if GetMonth() == 12 then "Z"
    else "") + Year);

def NC =
 open(period = p, symbol =
    "/VX" +
    (    if GetMonth() == 12 then "F"
    else if GetMonth() == 01 then "G"
    else if GetMonth() == 02 then "H"
    else if GetMonth() == 03 then "J"
    else if GetMonth() == 04 then "K"
    else if GetMonth() == 05 then "M"
    else if GetMonth() == 06 then "N"
    else if GetMonth() == 07 then "Q"
    else if GetMonth() == 08 then "U"
    else if GetMonth() == 09 then "V"
    else if GetMonth() == 10 then "X"
    else if GetMonth() == 11 then "Z"
    else "") + (Year + (GetMonth() == 12))
);

def Exp =
    IsNaN(CC[-1])
    && !IsNaN(CC)
    && !isNaN(close[-1]);
# && close
#    && !IsNaN(NC);

def xPrice =
    CC[1];
def nPrice =
    NC;

def Cur =
    If (Exp, nPrice, Cur[1]);
def Pri =
    If (Exp, xPrice, Pri[1]);
def Mid =
    (Cur + Pri) / 2;

AddVerticalLine(
    Exp && aggDaily, "", Color.WHITE);
AddChartBubble(Exp && aggDaily, high,
    "Exp Close: " + xPrice + "\nMid: " + Mid + "\nNext Open: " + nPrice
, Color.WHITE);

plot x = if(aggDaily,Cur,Double.NAN);
x.SetPaintingStrategy(12);
plot y = if(aggDaily,Pri,Double.NAN);
y.SetPaintingStrategy(12);
plot z = if(aggDaily,Mid,Double.NAN);
z.SetPaintingStrategy(12);

input showBubble = yes;
input bubblemover = 1;
def   b = bubblemover;

AddChartBubble(aggDaily && showBubble && IsNaN(close[b]) && !IsNaN(close[b + 1]), Pri[b + 1], "Close " + Pri[b + 1], Color.GREEN);
AddChartBubble(aggDaily && showBubble && IsNaN(close[b]) && !IsNaN(close[b + 1]), Cur[b + 1], "Open " + Cur[b + 1], Color.GREEN);
AddChartBubble(aggDaily && showBubble && IsNaN(close[b]) && !IsNaN(close[b + 1]), Mid[b + 1], "Mid " + Mid[b + 1], Color.PINK);

def vxClose = if !IsNaN(close(period = p, symbol = "/VX")) then close(period = p, symbol = "/VX") else close(period = p, symbol = "/VX")[1];

AddLabel(aggDaily && yes, "/VX: " + AsText(vxClose) + "   Mid: " + AsText(Mid), if vxClose > Mid then Color.RED
    else if vxClose < Mid then Color.GREEN
    else Color.ORANGE, Location, FontSize);

AddLabel(!aggDaily, "VX Study Must Be on a Daily Chart > 1 month", Color.RED);
ThisIsWhatIhave.png
ThisIsWhatIwantAtExpiraton.png
 
Last edited:
Final working study.

This study is designed to interpret market conditions by analyzing the behavior of volatility through /VX (VIX futures). It focuses on where the current /VX level sits relative to a calculated expected move range—specifically the upper, lower, and midpoint levels—and uses that relationship to classify the market environment.

When /VX is below the midpoint, volatility is relatively subdued, which typically corresponds to more stable or trend-friendly market behavior. When /VX is near the midpoint, the market is in a balanced state with no strong volatility bias. When /VX rises above the midpoint, volatility is elevated beyond expectations, often signaling a less stable environment where price action can become erratic or “irrational.”

The study also incorporates the volatility term structure—contango versus backwardation—to add context. In contango, longer-dated /VX futures are priced higher than near-term contracts, reflecting normal conditions and generally lower immediate risk. In backwardation, near-term contracts are priced higher than longer-dated ones, indicating heightened short-term fear or demand for protection, which is typically associated with market stress.

By combining the current /VX level with its position relative to the midpoint and the broader term structure, the study provides a structured way to assess whether the market is operating under stable conditions, elevated risk, or potential instability.
VIX Futures Contango Indicator.png

Code:
# =====================================================================
# OBJECTIVE:
# Provide a clear, context-aware visualization of volatility structure
# using /VX (CBOE Volatility Index futures) to assess market regime,
# directional risk, and sentiment bias.

# PURPOSE:
# This study evaluates the relationship between the current /VX level
# and its derived expected move structure (Upper, Lower, Mid) to
# characterize volatility conditions and broader market context.

# Key Interpretations:
# - When /VX is below Mid:
#     Indicates relatively suppressed volatility and typically aligns
#     with stable or trend-supportive market conditions.

# - When /VX is near Mid:
#     Represents equilibrium in volatility expectations; market is
#     balanced with no strong volatility bias.

# - When /VX is above Mid:
#     Signals elevated volatility relative to baseline expectations.
#     This condition may reflect an "irrational" or unstable market
#     environment where price behavior becomes less orderly and more
#     reactive.

# Term Structure Context:
# - Contango:
#     Longer-dated /VX futures priced higher than near-term contracts.
#     Implies normal market conditions with expectations of rising
#     volatility over time; generally associated with stable equity
#     markets.

# - Backwardation:
#     Near-term /VX futures priced higher than longer-dated contracts.
#     Indicates immediate demand for protection and elevated risk;
#     commonly observed during stress events or market dislocations.

# Combined Interpretation:
# - /VX above Mid + Backwardation:
#     High-risk regime; volatility is both elevated and front-loaded,
#     suggesting potential instability or panic-driven conditions.

# - /VX below Mid + Contango:
#     Lower-risk regime; volatility is subdued and term structure is
#     normal, supporting more stable price action.

# This framework is intended to enhance situational awareness by
# integrating volatility level and structure into a unified read of
# market conditions.
# =====================================================================

declare upper;

input FontSize  = FontSize.SMALL;
input Location  = Location.TOP_LEFT;

input showLevels     = yes;
input showExpMarkers = yes;

input showEndBubbles = yes;
input bubblemover    = 0;

# ----------------------------------------------------------------------
# GLOBAL COLORS
# ----------------------------------------------------------------------
DefineGlobalColor("Cur", Color.GREEN);
DefineGlobalColor("Pri", Color.RED);
DefineGlobalColor("Mid", Color.LIGHT_GRAY);

def isDaily = GetAggregationPeriod() == AggregationPeriod.DAY;

# -------------------------------------------------
# Helpers: VX contract close / open (DAY only)
# -------------------------------------------------
script VXClose {
    input m  = 1;
    input y2 = 25;
    plot v =
        close(
            period = AggregationPeriod.DAY,
            symbol =
                "/VX" +
                (if m == 1 then "F"
                 else if m == 2 then "G"
                 else if m == 3 then "H"
                 else if m == 4 then "J"
                 else if m == 5 then "K"
                 else if m == 6 then "M"
                 else if m == 7 then "N"
                 else if m == 8 then "Q"
                 else if m == 9 then "U"
                 else if m == 10 then "V"
                 else if m == 11 then "X"
                 else "Z") +
                y2
        );
}

script VXOpen {
    input m  = 1;
    input y2 = 25;
    plot v =
        open(
            period = AggregationPeriod.DAY,
            symbol =
                "/VX" +
                (if m == 1 then "F"
                 else if m == 2 then "G"
                 else if m == 3 then "H"
                 else if m == 4 then "J"
                 else if m == 5 then "K"
                 else if m == 6 then "M"
                 else if m == 7 then "N"
                 else if m == 8 then "Q"
                 else if m == 9 then "U"
                 else if m == 10 then "V"
                 else if m == 11 then "X"
                 else "Z") +
                y2
        );
}

# -------------------------------------------------
# /VX continuous close (reference)
# -------------------------------------------------
def vxClose = close(period = AggregationPeriod.DAY, symbol = "/VX");

# -------------------------------------------------
# Candidate contracts: current month .. +5 months
# -------------------------------------------------
def baseM  = GetMonth();
def baseY2 = Floor(GetYear() % 100);

def m0 = baseM;
def y0 = baseY2;

def m1raw = baseM + 1;
def m1 = if m1raw > 12 then m1raw - 12 else m1raw;
def y1 = baseY2 + (m1raw > 12);

def m2raw = baseM + 2;
def m2 = if m2raw > 12 then m2raw - 12 else m2raw;
def y2n = baseY2 + (m2raw > 12);

def m3raw = baseM + 3;
def m3 = if m3raw > 12 then m3raw - 12 else m3raw;
def y3 = baseY2 + (m3raw > 12);

def m4raw = baseM + 4;
def m4 = if m4raw > 12 then m4raw - 12 else m4raw;
def y4 = baseY2 + (m4raw > 12);

def m5raw = baseM + 5;
def m5 = if m5raw > 12 then m5raw - 12 else m5raw;
def y5 = baseY2 + (m5raw > 12);

# Stable contract IDs (YYMM)
def id0 = y0 * 100 + m0;
def id1 = y1 * 100 + m1;
def id2 = y2n * 100 + m2;
def id3 = y3 * 100 + m3;
def id4 = y4 * 100 + m4;
def id5 = y5 * 100 + m5;

# Contract series
def c0 = VXClose(m0, y0);
def o0 = VXOpen (m0, y0);

def c1 = VXClose(m1, y1);
def o1 = VXOpen (m1, y1);

def c2 = VXClose(m2, y2n);
def o2 = VXOpen (m2, y2n);

def c3 = VXClose(m3, y3);
def o3 = VXOpen (m3, y3);

def c4 = VXClose(m4, y4);
def o4 = VXOpen (m4, y4);

def c5 = VXClose(m5, y5);
def o5 = VXOpen (m5, y5);

# -------------------------------------------------
# Best-match contract index (closest to /VX close)
# -------------------------------------------------
def big = 1000000.0;

def d0 = if IsNaN(c0) then big else AbsValue(vxClose - c0);
def d1 = if IsNaN(c1) then big else AbsValue(vxClose - c1);
def d2 = if IsNaN(c2) then big else AbsValue(vxClose - c2);
def d3 = if IsNaN(c3) then big else AbsValue(vxClose - c3);
def d4 = if IsNaN(c4) then big else AbsValue(vxClose - c4);
def d5 = if IsNaN(c5) then big else AbsValue(vxClose - c5);

def min01  = Min(d0, d1);
def idx01  = if d0 <= d1 then 0 else 1;

def min012 = Min(min01, d2);
def idx012 = if min01 <= d2 then idx01 else 2;

def min0123 = Min(min012, d3);
def idx0123 = if min012 <= d3 then idx012 else 3;

def min01234 = Min(min0123, d4);
def idx01234 = if min0123 <= d4 then idx0123 else 4;

def bestIdx = if min01234 <= d5 then idx01234 else 5;

# Stable chosen contract ID (YYMM)
def bestID =
    if bestIdx == 0 then id0
    else if bestIdx == 1 then id1
    else if bestIdx == 2 then id2
    else if bestIdx == 3 then id3
    else if bestIdx == 4 then id4
    else id5;

# -------------------------------------------------
# Rollover detection (first day after expiration)
# -------------------------------------------------
def rollToday =
    isDaily and
    !IsNaN(vxClose) and
    !IsNaN(vxClose[1]) and
    bestID != bestID[1];

# -------------------------------------------------
# Expiring close (yesterday) and next open (today)
# -------------------------------------------------
def expClose =
    if bestIdx == 0 then c0
    else if bestIdx == 1 then c1
    else if bestIdx == 2 then c2
    else if bestIdx == 3 then c3
    else if bestIdx == 4 then c4
    else c5;

def nextOpenToday =
    if bestIdx == 0 then o0
    else if bestIdx == 1 then o1
    else if bestIdx == 2 then o2
    else if bestIdx == 3 then o3
    else if bestIdx == 4 then o4
    else o5;

# Persist levels (update on rollover day)
def Cur = if rollToday then nextOpenToday else Cur[1];
def Pri = if rollToday then expClose[1] else Pri[1];
def Mid = (Cur + Pri) / 2;

# -------------------------------------------------
# Markers (FIRST DAY AFTER EXPIRATION / ROLLOVER DAY)
# -------------------------------------------------
AddVerticalLine(isDaily and showExpMarkers and rollToday, "", Color.WHITE);

AddChartBubble(
    isDaily and showExpMarkers and rollToday,
    high,
    "Exp Close: " + AsText(Pri) +
    "\nMid: " + AsText(Mid) +
    "\nNext Open: " + AsText(Cur),
    Color.WHITE
);

# -------------------------------------------------
# Horizontal levels
# -------------------------------------------------
plot x = if isDaily and showLevels then Cur else Double.NaN;
x.SetPaintingStrategy(12);
x.SetDefaultColor(GlobalColor("Cur"));
x.SetLineWeight(2);

plot y = if isDaily and showLevels then Pri else Double.NaN;
y.SetPaintingStrategy(12);
y.SetDefaultColor(GlobalColor("Pri"));
y.SetLineWeight(2);

plot z = if isDaily and showLevels then Mid else Double.NaN;
z.SetPaintingStrategy(12);
z.SetDefaultColor(GlobalColor("Mid"));
z.SetLineWeight(1);

# -------------------------------------------------
# End-of-series bubbles
# -------------------------------------------------
def b = bubblemover;

AddChartBubble(isDaily and showEndBubbles and IsNaN(close[b]) and !IsNaN(close[b + 1]),
    Pri[b + 1], "Close " + AsText(Pri[b + 1]), Color.PINK);
AddChartBubble(isDaily and showEndBubbles and IsNaN(close[b]) and !IsNaN(close[b + 1]),
    Cur[b + 1], "Open " + AsText(Cur[b + 1]), Color.GREEN);
AddChartBubble(isDaily and showEndBubbles and IsNaN(close[b]) and !IsNaN(close[b + 1]),
    Mid[b + 1], "Mid " + AsText(Mid[b + 1]), Color.WHITE);

# -------------------------------------------------
# Label
# -------------------------------------------------
AddLabel(isDaily,
    "/VX: " + AsText(vxClose) + "   Mid: " + AsText(Mid),
    if vxClose > Mid then Color.RED
    else if vxClose < Mid then Color.GREEN
    else Color.ORANGE,
    Location, FontSize);

AddLabel(!isDaily, "VX Study Must Be on a Daily Chart > 1 month", Color.RED);
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
771 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top