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: 85

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