Twap-Vwap Difference

germanburrito

Active member
Hello! I haven’t been here in a while, but here’s the idea:

I have two indicators, TWAP (Time-Weighted Average Price) and VWAP (Volume-Weighted Average Price). I’m trying to create a cumulative indicator to track whether VWAP is too far away from TWAP over time.

  • TWAP calculates the price across time.
  • VWAP calculates the price with volume considered across time.
What I want to do is create an indicator that will add or subtract the difference between TWAP and VWAP at the end of each day. This will help me determine if VWAP is too high or too far from the time-based TWAP, which would signal market imbalance. By doing so, I can better understand if there’s too much deviation in the price relative to volume.

here is the starting code
Code:
input price = ohlc4;
input timeFrame = {default Day, Week, Month, Chart};

# Define the period index for the selected timeframe
def yyyyMmDd = GetYYYYMMDD();
def periodIndx;
switch (timeFrame) {
case Day:
    periodIndx = yyyyMmDd;
case Week:
    periodIndx = Floor((DaysFromDate(First(yyyyMmDd)) + GetDayOfWeek(First(yyyyMmDd))) / 7);
case Month:
    periodIndx = RoundDown(yyyyMmDd / 100, 0);
case Chart:
    periodIndx = 0;
}

# Detect new day
def newDay = CompoundValue(1, periodIndx != periodIndx[1], yes);
def isCloseTime = SecondsTillTime(1600) == 0;

# TWAP Calculation
def cumePrice = if newDay then price else price + cumePrice[1];
def cumeBarNumber = if newDay then 1 else 1 + cumeBarNumber[1];
def TWAP_Price = Round(cumePrice / cumeBarNumber, 4);
plot TWAP = TWAP_Price;

# VWAP Calculation
def isPeriodRolled = CompoundValue(1, periodIndx != periodIndx[1], yes);
def volumeSum;
def volumeVWAPSum;

if (isPeriodRolled) {
    volumeSum = volume;
    volumeVWAPSum = volume * vwap;
} else {
    volumeSum = CompoundValue(1, volumeSum[1] + volume, volume);
    volumeVWAPSum = CompoundValue(1, volumeVWAPSum[1] + volume * vwap, volume * vwap);
}
def VWAP = volumeVWAPSum / volumeSum;
plot VWAP_Plot = VWAP;

# Difference Calculation (VWAP - TWAP) at the close
def dailyDifference = if isCloseTime then VWAP - TWAP else Double.NaN;
def lastValidDifference = if !IsNaN(dailyDifference) then dailyDifference else lastValidDifference[1];

# Accumulated Total Difference
def totalDifference = CompoundValue(1, if newDay then totalDifference[1] + lastValidDifference else totalDifference[1], 0);

# Debugging Labels
AddLabel(yes, "Daily Difference (VWAP - TWAP): " + AsText(lastValidDifference), if lastValidDifference >= 0 then Color.GREEN else Color.RED);
AddLabel(yes, "Accumulated Total: " + AsText(totalDifference), if totalDifference >= 0 then Color.GREEN else Color.RED);

# Debugging Plots (Temporary for Verification)
plot DebugDailyDiff = if !IsNaN(dailyDifference) then dailyDifference else Double.NaN;
DebugDailyDiff.SetDefaultColor(Color.MAGENTA);
DebugDailyDiff.SetLineWeight(2);

plot DebugTotalDiff = totalDifference;
DebugTotalDiff.SetDefaultColor(Color.YELLOW);
DebugTotalDiff.SetLineWeight(2);

# Styling
VWAP_Plot.SetDefaultColor(Color.BLUE);
TWAP.SetDefaultColor(Color.ORANGE);

AddCloud(VWAP, TWAP, Color.GREEN, Color.RED);
VWAP_Plot.SetLineWeight(2);
TWAP.SetLineWeight(2);
 

Attachments

  • Screenshot 2024-12-09 161628.jpg
    Screenshot 2024-12-09 161628.jpg
    89.8 KB · Views: 359
Solution
@samer800 might be able to help with this? Thank you
no sure if this what you wanted

CSS:
input price = vwap;
#input timeFrame = {default Day, Week, Month};

def na = Double.NaN;
# Define the period index for the selected timeframe
def yyyyMmDd = GetYYYYMMDD();

# Detect new day
def time = GetTime();
def RTH = time >= RegularTradingStart(yyyyMmDd) and time <= RegularTradingEnd(yyyyMmDd);
def cntTH = if RTH!=RTH[1] then yes else cntTH[1];
def newDay = CompoundValue(1, yyyyMmDd != yyyyMmDd[1], yes);

def isCloseTime = if cntTH then (RTH and !RTH[-1]) else newDay[-1];


# VWAP/TWAP Calculation
def cumPrice;
def cumBarNumber;
def volumeSum;
def volumeVWAPSum;
if (newDay) {
    cumPrice = price;
    cumBarNumber = 1...
Have you made any improvements on the script?

Here is one change I thought of, credit minor adjustments mostly to Grok

Code:
input price = ohlc4;
input timeFrame = {default Day, Week, Month, Chart};
input anchorDays = 15;

# Define the period index for the selected timeframe
def yyyyMmDd = GetYYYYMMDD();
def periodIndx;
switch (timeFrame) {
    case Day:
        periodIndx = yyyyMmDd;
    case Week:
        periodIndx = Floor((DaysFromDate(First(yyyyMmDd)) + GetDayOfWeek(First(yyyyMmDd))) / 7);
    case Month:
        periodIndx = RoundDown(yyyyMmDd / 100, 0);
    case Chart:
        periodIndx = 0;
}

# Detect new period based on the anchorDays
def daysSinceStart = if GetDay() == GetDay()[1] then daysSinceStart[1] + 1 else 1;
def isAnchorStart = daysSinceStart == 1;

# TWAP Calculation with carry over
def cumePrice = if isAnchorStart then cumePrice[1] else CompoundValue(1, cumePrice[1] + price, price);
def cumeBarNumber = if isAnchorStart then cumeBarNumber[1] else CompoundValue(1, cumeBarNumber[1] + 1, 1);
def TWAP_Price = if !IsNaN(cumePrice) then Round(cumePrice / cumeBarNumber, 4) else Double.NaN;
plot TWAP = TWAP_Price;

# VWAP Calculation with carry over
def volumeSum = if isAnchorStart then volumeSum[1] else CompoundValue(1, volumeSum[1] + volume, volume);
def volumeVwapSum = if isAnchorStart then volumeVwapSum[1] else CompoundValue(1, volumeVwapSum[1] + volume * price, volume * price);
def VWAP = if !IsNaN(volumeSum) then volumeVwapSum / volumeSum else Double.NaN;
plot VWAP_Plot = VWAP;

# Difference Calculation (VWAP - TWAP) at the close
def isCloseTime = SecondsTillTime(1600) == 0;
def dailyDifference = if isCloseTime then VWAP - TWAP else Double.NaN;
def lastValidDifference = if !IsNaN(dailyDifference) then dailyDifference else lastValidDifference[1];

# Accumulated Total Difference
def totalDifference = CompoundValue(1, if isAnchorStart then 0 else totalDifference[1] + lastValidDifference, 0);

# Debugging Labels
AddLabel(yes, "Daily Difference (VWAP - TWAP): " + AsText(lastValidDifference), if lastValidDifference >= 0 then Color.GREEN else Color.RED);
AddLabel(yes, "Accumulated Total: " + AsText(totalDifference), if totalDifference >= 0 then Color.GREEN else Color.RED);

# Debugging Plots (Temporary for Verification)
plot DebugDailyDiff = if !IsNaN(dailyDifference) then dailyDifference else Double.NaN;
DebugDailyDiff.SetDefaultColor(Color.MAGENTA);
DebugDailyDiff.SetLineWeight(2);

plot DebugTotalDiff = totalDifference;
DebugTotalDiff.SetDefaultColor(Color.YELLOW);
DebugTotalDiff.SetLineWeight(2);

# Styling
VWAP_Plot.SetDefaultColor(Color.BLUE);
TWAP.SetDefaultColor(Color.ORANGE);

AddCloud(VWAP, TWAP, Color.GREEN, Color.RED);
VWAP_Plot.SetLineWeight(2);
TWAP.SetLineWeight(2);
 
Last edited by a moderator:
Have you made any improvements on the script?

Here is one change I thought of, credit minor adjustments mostly to Grok

Code:
input price = ohlc4;
input timeFrame = {default Day, Week, Month, Chart};
input anchorDays = 15;

# Define the period index for the selected timeframe
def yyyyMmDd = GetYYYYMMDD();
def periodIndx;
switch (timeFrame) {
    case Day:
        periodIndx = yyyyMmDd;
    case Week:
        periodIndx = Floor((DaysFromDate(First(yyyyMmDd)) + GetDayOfWeek(First(yyyyMmDd))) / 7);
    case Month:
        periodIndx = RoundDown(yyyyMmDd / 100, 0);
    case Chart:
        periodIndx = 0;
}

# Detect new period based on the anchorDays
def daysSinceStart = if GetDay() == GetDay()[1] then daysSinceStart[1] + 1 else 1;
def isAnchorStart = daysSinceStart == 1;

# TWAP Calculation with carry over
def cumePrice = if isAnchorStart then cumePrice[1] else CompoundValue(1, cumePrice[1] + price, price);
def cumeBarNumber = if isAnchorStart then cumeBarNumber[1] else CompoundValue(1, cumeBarNumber[1] + 1, 1);
def TWAP_Price = if !IsNaN(cumePrice) then Round(cumePrice / cumeBarNumber, 4) else Double.NaN;
plot TWAP = TWAP_Price;

# VWAP Calculation with carry over
def volumeSum = if isAnchorStart then volumeSum[1] else CompoundValue(1, volumeSum[1] + volume, volume);
def volumeVwapSum = if isAnchorStart then volumeVwapSum[1] else CompoundValue(1, volumeVwapSum[1] + volume * price, volume * price);
def VWAP = if !IsNaN(volumeSum) then volumeVwapSum / volumeSum else Double.NaN;
plot VWAP_Plot = VWAP;

# Difference Calculation (VWAP - TWAP) at the close
def isCloseTime = SecondsTillTime(1600) == 0;
def dailyDifference = if isCloseTime then VWAP - TWAP else Double.NaN;
def lastValidDifference = if !IsNaN(dailyDifference) then dailyDifference else lastValidDifference[1];

# Accumulated Total Difference
def totalDifference = CompoundValue(1, if isAnchorStart then 0 else totalDifference[1] + lastValidDifference, 0);

# Debugging Labels
AddLabel(yes, "Daily Difference (VWAP - TWAP): " + AsText(lastValidDifference), if lastValidDifference >= 0 then Color.GREEN else Color.RED);
AddLabel(yes, "Accumulated Total: " + AsText(totalDifference), if totalDifference >= 0 then Color.GREEN else Color.RED);

# Debugging Plots (Temporary for Verification)
plot DebugDailyDiff = if !IsNaN(dailyDifference) then dailyDifference else Double.NaN;
DebugDailyDiff.SetDefaultColor(Color.MAGENTA);
DebugDailyDiff.SetLineWeight(2);

plot DebugTotalDiff = totalDifference;
DebugTotalDiff.SetDefaultColor(Color.YELLOW);
DebugTotalDiff.SetLineWeight(2);

# Styling
VWAP_Plot.SetDefaultColor(Color.BLUE);
TWAP.SetDefaultColor(Color.ORANGE);

AddCloud(VWAP, TWAP, Color.GREEN, Color.RED);
VWAP_Plot.SetLineWeight(2);
TWAP.SetLineWeight(2);
@samer800 might be able to help with this? Thank you
 
@samer800 might be able to help with this? Thank you
no sure if this what you wanted

CSS:
input price = vwap;
#input timeFrame = {default Day, Week, Month};

def na = Double.NaN;
# Define the period index for the selected timeframe
def yyyyMmDd = GetYYYYMMDD();

# Detect new day
def time = GetTime();
def RTH = time >= RegularTradingStart(yyyyMmDd) and time <= RegularTradingEnd(yyyyMmDd);
def cntTH = if RTH!=RTH[1] then yes else cntTH[1];
def newDay = CompoundValue(1, yyyyMmDd != yyyyMmDd[1], yes);

def isCloseTime = if cntTH then (RTH and !RTH[-1]) else newDay[-1];


# VWAP/TWAP Calculation
def cumPrice;
def cumBarNumber;
def volumeSum;
def volumeVWAPSum;
if (newDay) {
    cumPrice = price;
    cumBarNumber = 1;
    volumeSum = volume;
    volumeVWAPSum = volume * price;
} else {
    cumPrice = CompoundValue(1, cumPrice[1] + price, price);
    cumBarNumber = CompoundValue(1, cumBarNumber[1] + 1, 1);
    volumeSum = CompoundValue(1, volumeSum[1] + volume, volume);
    volumeVWAPSum = CompoundValue(1, volumeVWAPSum[1] + volume * price, volume * price);
}
def TWAP = cumPrice / cumBarNumber;
def VWAP = volumeVWAPSum / volumeSum;

def TWAP_Plot = if TWAP then TWAP else na;
plot VWAP_Plot = if VWAP then VWAP else na;

VWAP_Plot.SetDefaultColor(GetColor(0));

AddCloud(TWAP_Plot, VWAP_Plot, Color.GREEN, Color.RED);

# Difference Calculation (VWAP - TWAP) at the close
def differance = TWAP_Plot - VWAP_Plot;
def dailyDifference = if isCloseTime then differance[1] else dailyDifference[1];
def lastValidDifference = if newDay then close + dailyDifference else lastValidDifference[1];

# Accumulated Total Difference
def totalDifference = CompoundValue(1, if newDay then totalDifference[1] + dailyDifference else totalDifference[1], 0);

# Debugging Labels
AddLabel(yes, "Daily Difference (TWAP - VWAP): " + AsText(dailyDifference), if dailyDifference >= 0 then Color.GREEN else Color.RED);
AddLabel(yes, "Accumulated Total: " + AsText(totalDifference), if totalDifference >= 0 then Color.GREEN else Color.RED);

#

plot DebugTotalDiff = if lastValidDifference then lastValidDifference else na; #CompoundValue(1, totalDifference,  close(Period = "DAY"));
DebugTotalDiff.SetDefaultColor(Color.CYAN);
DebugTotalDiff.SetPaintingStrategy(PaintingStrategy.DASHES);
DebugTotalDiff.SetLineWeight(2);



#-- END of CODE
@germanburrito @8ix
 
Last edited by a moderator:
Solution

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
308 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