Plese convert VWAP TradingView strategy to ProRealTime

Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #249124 quote
    pete2626
    Participant
    New

    //@version=5
    strategy(“NASDAQ 100 Strategy”, overlay=true,
    default_qty_type=strategy.percent_of_equity,
    default_qty_value=1.5,
    process_orders_on_close=true) // Added to prevent intrabar repainting

    // User-configurable inputs
    initialCapital = input.float(10000, “Initial Capital ($)”, minval=1000, step=1000)
    equityPercentPerTrade = input.float(1.5, “Equity % per Trade”, minval=0.1, maxval=100, step=0.1)

    // Time settings – using session.ismarket to prevent time-based repainting
    isRegularSession = time(“1”, “0800-1600”)
    isExtendedSession = time(“1”, “0800-1600”)

    // Indicator settings
    longTermEmaLength = input.int(21, “Long Term EMA Length”, minval=5)
    shortTermEmaLength = input.int(9, “Short Term EMA Length”, minval=3)
    rsiLength = input.int(14, “RSI Length”, minval=5)
    atrLength = input.int(14, “ATR Length”, minval=5)

    // Risk management inputs
    trailStopATRMultiplier = input.float(1.5, “Trail Stop ATR Multiplier”, minval=0.5, step=0.1)
    initialStopLossMultiplier = input.float(0.5, “Initial Stop Loss Multiplier”, minval=0.1, step=0.1)
    breakEvenTriggerMultiplier = input.float(1.5, “Break-even Trigger Multiplier”, minval=0.5, step=0.1)
    timeExitBars = input.int(20, “Time Exit Bars”, minval=5)
    maxDrawdown = input.float(20, “Max Drawdown %”, minval=1, maxval=50)

    // Calculate position size
    tradeQty = (initialCapital * equityPercentPerTrade / 100) / close

    // Non-repainting indicators
    vwap = ta.vwap(hlc3)
    longTermEma = ta.ema(close, longTermEmaLength)
    shortTermEma = ta.ema(close, shortTermEmaLength)
    rsi = ta.rsi(close, rsiLength)
    atr = ta.atr(atrLength)
    volatilityFilter = ta.valuewhen(barstate.isconfirmed, atr > ta.sma(atr, 20), 0)

    // EMA directions calculated on confirmed bars only
    longEmaDirection = ta.valuewhen(barstate.isconfirmed, longTermEma > longTermEma[1], 0)
    shortEmaDirection = ta.valuewhen(barstate.isconfirmed, shortTermEma > shortTermEma[1], 0)

    isTradeWindow = isExtendedSession and volatilityFilter

    // Conditions – evaluated only on bar close
    longCondition = barstate.isconfirmed and (close > shortTermEma) and
    (shortTermEma > longTermEma) and longEmaDirection and
    shortEmaDirection and (rsi > 50) and (close > vwap) and
    isTradeWindow and isRegularSession

    shortCondition = barstate.isconfirmed and (close < shortTermEma) and
    (shortTermEma < longTermEma) and not longEmaDirection and
    not shortEmaDirection and (rsi < 50) and (close < vwap) and isTradeWindow and isRegularSession // Entry/Exit tracking var int longEntryBar = na var int shortEntryBar = na var float longEntryPrice = na var float shortEntryPrice = na // Execute trades only on confirmed bars if (longCondition) strategy.entry(“Long”, strategy.long, qty=tradeQty) longEntryBar := bar_index longEntryPrice := close if (shortCondition) strategy.entry(“Short”, strategy.short, qty=tradeQty) shortEntryBar := bar_index shortEntryPrice := close // Exit logic – non-repainting strategy.exit(“Exit Long”, “Long”, stop=longEntryPrice – atr * initialStopLossMultiplier, trail_points=atr * trailStopATRMultiplier, trail_offset=atr * trailStopATRMultiplier / 2) strategy.exit(“Exit Short”, “Short”, stop=shortEntryPrice + atr * initialStopLossMultiplier, trail_points=atr * trailStopATRMultiplier, trail_offset=atr * trailStopATRMultiplier / 2) // Break-even logic – non-repainting breakEvenTrigger = breakEvenTriggerMultiplier * atr if (strategy.position_size > 0 and close > longEntryPrice + breakEvenTrigger)
    strategy.exit(“Break-even Long”, “Long”, stop=longEntryPrice)
    if (strategy.position_size < 0 and close < shortEntryPrice – breakEvenTrigger) strategy.exit(“Break-even Short”, “Short”, stop=shortEntryPrice) // Time-based exit – non-repainting if (not na(longEntryBar) and bar_index – longEntryBar >= timeExitBars)
    strategy.close(“Long”)
    longEntryBar := na
    if (not na(shortEntryBar) and bar_index – shortEntryBar >= timeExitBars)
    strategy.close(“Short”)
    shortEntryBar := na

    // Trend reversal exit – non-repainting
    trendReversalExitLong = barstate.isconfirmed and (shortTermEma < longTermEma) and not longEmaDirection trendReversalExitShort = barstate.isconfirmed and (shortTermEma > longTermEma) and not shortEmaDirection

    if (strategy.position_size > 0 and trendReversalExitLong)
    strategy.close(“Long”)
    if (strategy.position_size < 0 and trendReversalExitShort)
    strategy.close(“Short”)

    // Max drawdown protection
    if (strategy.equity / initialCapital < 1 – (maxDrawdown / 100.0))
    strategy.cancel_all()
    strategy.close_all()

    // Plotting (non-repainting)
    plot(vwap, “VWAP”, color=color.purple, linewidth=2)
    plot(longTermEma, “Long EMA”, color=color.blue, linewidth=2)
    plot(shortTermEma, “Short EMA”, color=color.orange, linewidth=2)

    // Labels only on bar close
    if barstate.isconfirmed
    label.new(bar_index, high, “RSI: ” + str.tostring(rsi, “#.00”),
    color=color.rgb(0, 0, 0, 80), textcolor=color.white,
    style=label.style_label_center, yloc=yloc.price, size=size.small)

    label.new(bar_index, low, “ATR: ” + str.tostring(atr, “#.00”),
    color=color.rgb(0, 0, 0, 80), textcolor=color.white,
    style=label.style_label_center, yloc=yloc.price, size=size.small)

    #249156 quote
    Iván González
    Moderator
    Master

    Here you have.

    // --- USER CONFIGURATION PARAMETERS ---
    initialcapital = 100000 // Initial capital in USD
    // Percentage of equity to risk per trade
    longtermemalength = 21 // Long-term EMA period
    shorttermemalength = 9  // Short-term EMA period
    rsilength = 14           // RSI period
    atrlength = 14           // ATR period
    trailstopatrmultiplier = 1.5 // Trailing stop multiplier based on ATR
    initialstoplossmultiplier = 0.5 // Initial stop loss multiplier based on ATR
    breakeventriggermultiplier = 1.5 // Breakeven trigger multiplier based on ATR
    timeexitbars = 20             // Max holding time (bars)
    maxdrawdown = 20              // Maximum drawdown protection (%)
    startvwap=170000              // VWAP reset time (hhmmss format)
    Startsession=80000            // Market session start time (hhmmss)
    EndSession=160000             // Market session end time (hhmmss)
    
    // --- INDICATORS ---
    // --- VWAP Calculation ---
    if opentime>=startvwap and opentime[1]<startvwap then
       d=1
       VWAP=typicalprice
    else
       d=d+1
       if volume >0 then
          VWAP = SUMMATION[d](volume*typicalprice)/SUMMATION[d](volume)
       endif
    endif
    
    // --- Exponential Moving Averages ---
    longema = average[longtermemalength,1](close) // Long-term EMA
    shortema = average[shorttermemalength,1](close) // Short-term EMA
    
    // --- RSI Indicator ---
    myrsi = RSI[rsilength](close)
    
    // --- ATR Indicator ---
    atr = AverageTrueRange[atrlength](close)
    
    // --- VOLATILITY FILTER (active only when ATR > average ATR over 20 bars) ---
    volatilityfilter = atr > average[20](atr)
    
    // --- EMA DIRECTION FILTER (both EMAs must slope upwards/downwards) ---
    longemadirection = longema > longema[1]
    shortemadirection = shortema > shortema[1]
    
    // --- TRADING SESSION TIME FILTER ---
    inmarkettime = (opentime >= StartSession AND opentime <= EndSession)
    
    // --- POSITION SIZE AND EQUITY TRACKING ---
    equity = initialcapital + strategyprofit
    
    // --- MAXIMUM DRAWDOWN PROTECTION ---
    IF (equity / initialcapital) < (1 - (maxdrawdown / 100)) THEN
       quit // Exit all trades and stop the strategy
    ENDIF
    
    // --- LONG ENTRY CONDITION ---
    longcondition = close > shortema AND shortema > longema AND longemadirection AND shortemadirection AND myrsi > 50 AND close > vwap AND volatilityfilter AND inmarkettime
    
    // --- SHORT ENTRY CONDITION ---
    shortcondition = close < shortema AND shortema < longema AND longemadirection=0 AND shortemadirection=0 AND myrsi < 50 AND close < vwap AND volatilityfilter AND inmarkettime
    
    // --- ENTRY VARIABLES TRACKING ---
    ONCE longentryprice = 0
    ONCE shortentryprice = 0
    ONCE longentrybar = 0
    ONCE shortentrybar = 0
    
    // --- ORDER EXECUTION LOGIC ---
    IF not longonmarket and longcondition THEN
       BUY 1 contract AT MARKET
       longentrybar = barindex
    ENDIF
    
    IF not shortonmarket and shortcondition THEN
       SELLSHORT 1 contract AT MARKET
       shortentrybar = barindex
    ENDIF
    
    // --- REAL-TIME FLOATING PROFIT CALCULATION ---
    floatingprofit = (((close-positionprice)*pointvalue)*abs(countofposition))/pointsize
    
    // --- INITIAL STOP LOSS AND TRAILING STOP CONFIGURATION ---
    IF longonmarket and longonmarket[1]=0 THEN
       longentryprice = tradeprice
       stoploss = longentryprice - atr * initialstoplossmultiplier
       SET STOP price stoploss
       SET STOP PTRAILING atr * trailstopatrmultiplier
    ENDIF
    
    IF shortonmarket and shortonmarket[1]=0 THEN
       shortentryprice = tradeprice
       stoploss = shortentryprice + atr * initialstoplossmultiplier
       SET STOP price stoploss
       SET STOP PTRAILING atr * trailstopatrmultiplier
    ENDIF
    
    // --- BREAK-EVEN LOGIC ---
    breakeventrigger = breakeventriggermultiplier * atr
    
    IF longonmarket AND close > longentryprice + breakeventrigger THEN
       SET STOP price longentryprice
    ENDIF
    
    IF shortonmarket AND close < shortentryprice - breakeventrigger THEN
       SET STOP price shortentryprice
    ENDIF
    
    // --- TIME-BASED EXIT (after N bars in trade) ---
    IF longonmarket AND (barindex - longentrybar >= timeexitbars) THEN
       sell at market
    ENDIF
    
    IF shortonmarket AND (barindex - shortentrybar >= timeexitbars) THEN
       EXITSHORT at market
    ENDIF
    
    // --- TREND REVERSAL EXIT ---
    trendreversalexitlong = shortema < longema AND NOT longemadirection
    trendreversalexitshort = shortema > longema AND NOT shortemadirection
    
    IF longonmarket AND trendreversalexitlong THEN
       sell at market
    ENDIF
    
    IF shortonmarket AND trendreversalexitshort THEN
       EXITSHORT at market
    ENDIF
    
    // --- CHART DISPLAY (VWAP and EMAs) ---
    graphonprice vwap COLOURED(128,0,128)         // VWAP in purple
    graphonprice longema COLOURED(0,0,255)        // Long EMA in blue
    graphonprice shortema COLOURED(255,165,0)     // Short EMA in orange
    
    pete2626 thanked this post
    #249178 quote
    pete2626
    Participant
    New

    Hi Ivan,

    Thanks again for sharing the strategy conversion! I really appreciate the time and effort you put into it. I’ve made a few adjustments on my end to better match the indicator I’m using on TradingView.

    That said, I noticed that the order entries on ProRealTime don’t quite line up with the ones from TradingView. I’ve been trying to figure out how to get them to match more closely, but I’m a bit stuck at this point.

    Would you mind taking a quick look or pointing me in the right direction? Any help would mean a lot.

    Thanks again for all your help so far! Below is the code where I made some adjustments:

    // — USER CONFIGURATION PARAMETERS — initialcapital = 100000 // Initial capital in USD // Percentage of equity to risk per trade longtermemalength = 21 // Long-term EMA period shorttermemalength = 9 // Short-term EMA period rsilength = 14 // RSI period atrlength = 14 // ATR period trailstopatrmultiplier = 1.5 // Trailing stop multiplier based on ATR initialstoplossmultiplier = 0.5 // Initial stop loss multiplier based on ATR breakeventriggermultiplier = 1.5 // Breakeven trigger multiplier based on ATR timeexitbars = 20 // Max holding time (bars) maxdrawdown = 20 // Maximum drawdown protection (%) startvwap=170000 // VWAP reset time (hhmmss format) Startsession=80000 // Market session start time (hhmmss) EndSession=160000 // Market session end time (hhmmss) // — INDICATORS — // === VWAP based on Typical Price, session anchored to UTC+8 === utc8ResetHour = 0 // Midnight UTC+8 brokerOffset = -9 // Your broker is on UTC; adjust as needed resetHour = (utc8ResetHour – brokerOffset + 24) mod 24 // Detect new session at UTC+8 newSession = (hour = resetHour and minute = 0) // Initialize accumulators if barindex = 0 or newSession then cumVolume = 0 cumPV = 0 endif // Calculate typical price tp = (high + low + close) / 3 // Accumulate volume and price×volume cumVolume = cumVolume + volume cumPV = cumPV + (tp * volume) // Compute VWAP (only when volume > 0) if cumVolume > 0 then vwap = cumPV / cumVolume else vwap = 0 endif // — Exponential Moving Averages — longema = average[longtermemalength,1](close[1]) // Long-term EMA shortema = average[shorttermemalength,1](close[1]) // Short-term EMA // — RSI Indicator — myrsi = RSI[rsilength](close) // — ATR Indicator — atr = AverageTrueRange[atrlength](close) // — VOLATILITY FILTER (active only when ATR > average ATR over 20 bars) — volatilityfilter = atr > average[20](atr) // — EMA DIRECTION FILTER (both EMAs must slope upwards/downwards) — longemadirection = longema > longema[1] shortemadirection = shortema > shortema[1] // — TRADING SESSION TIME FILTER — inmarkettime = (opentime >= StartSession AND opentime <= EndSession) // — POSITION SIZE AND EQUITY TRACKING — equity = initialcapital + strategyprofit // — MAXIMUM DRAWDOWN PROTECTION — IF (equity / initialcapital) < (1 – (maxdrawdown / 100)) THEN quit // Exit all trades and stop the strategy ENDIF // — LONG ENTRY CONDITION — longcondition = close > shortema AND shortema > longema AND longemadirection AND shortemadirection AND myrsi > 50 AND close > vwap AND volatilityfilter AND inmarkettime // — SHORT ENTRY CONDITION — shortcondition = close < shortema AND shortema < longema AND longemadirection=0 AND shortemadirection=0 AND myrsi < 50 AND close < vwap AND volatilityfilter AND inmarkettime // — ENTRY VARIABLES TRACKING — ONCE longentryprice = 0 ONCE shortentryprice = 0 ONCE longentrybar = 0 ONCE shortentrybar = 0 // — ORDER EXECUTION LOGIC — IF not longonmarket and longcondition THEN BUY 1 contract AT MARKET longentrybar = barindex ENDIF IF not shortonmarket and shortcondition THEN SELLSHORT 1 contract AT MARKET shortentrybar = barindex ENDIF // — REAL-TIME FLOATING PROFIT CALCULATION — floatingprofit = (((close-positionprice)*pointvalue)*abs(countofposition))/pointsize // — INITIAL STOP LOSS AND TRAILING STOP CONFIGURATION — IF longonmarket and longonmarket[1]=0 THEN longentryprice = tradeprice stoploss = longentryprice – atr * initialstoplossmultiplier SET STOP price stoploss SET STOP PTRAILING atr * trailstopatrmultiplier ENDIF IF shortonmarket and shortonmarket[1]=0 THEN shortentryprice = tradeprice stoploss = shortentryprice + atr * initialstoplossmultiplier SET STOP price stoploss SET STOP PTRAILING atr * trailstopatrmultiplier ENDIF // — BREAK-EVEN LOGIC — breakeventrigger = breakeventriggermultiplier * atr IF longonmarket AND close > longentryprice + breakeventrigger THEN SET STOP price longentryprice ENDIF IF shortonmarket AND close < shortentryprice – breakeventrigger THEN SET STOP price shortentryprice ENDIF // — TIME-BASED EXIT (after N bars in trade) — IF longonmarket AND (barindex – longentrybar >= timeexitbars) THEN sell at market ENDIF IF shortonmarket AND (barindex – shortentrybar >= timeexitbars) THEN EXITSHORT at market ENDIF // — TREND REVERSAL EXIT — trendreversalexitlong = shortema < longema AND NOT longemadirection trendreversalexitshort = shortema > longema AND NOT shortemadirection IF longonmarket AND trendreversalexitlong THEN sell at market ENDIF IF shortonmarket AND trendreversalexitshort THEN EXITSHORT at market ENDIF // — CHART DISPLAY (VWAP and EMAs) — graphonprice vwap COLOURED(128,0,128) // VWAP in purple graphonprice longema COLOURED(0,0,255) // Long EMA in blue graphonprice shortema COLOURED(255,165,0) // Short EMA in orange
    #249206 quote
    Nicolas
    Keymaster
    Master
    Hello, are you sure the data are exactly the same? Please compare the candlesticks OHLC between platforms to make sure. Also, if orders don’t line up between the 2 platforms, there are many reasons possible:
    • indicators calculation differences: a simple different rounding of a 2 decimals value can make a difference
    • these are 2 different platforms with their own backtest engine
    • spread
    • the PRT code you shared use a SET STOP TRAILING instruction which use its own way to trail orders ; I’m a 100% sure this is not the same in TV engine.
    Iván González thanked this post
    #249209 quote
    JS
    Participant
    Senior
    Hi,
    When I test your code, I get the same orders as in the TradingView indicator (see screenshot)… What I see in your screenshot is that you’re using the wrong contract: “US Tech 100 (100$)”… (this is the futures contract from IG with a point value of $100) If you use this contract, no positions will be opened because your capital is too low… The correct contract for this system is: US Tech 100 Cash (1$)…
    Iván González thanked this post
Viewing 5 posts - 1 through 5 (of 5 total)
  • You must be logged in to reply to this topic.

Plese convert VWAP TradingView strategy to ProRealTime


ProBuilder: Indicators & Custom Tools

New Reply
Author
author-avatar
pete2626 @pete2626 Participant
Summary

This topic contains 4 replies,
has 4 voices, and was last updated by JS
6 months, 1 week ago.

Topic Details
Forum: ProBuilder: Indicators & Custom Tools
Language: English
Started: 07/26/2025
Status: Active
Attachments: 3 files
Logo Logo
Loading...