ProRealCode - Trading & Coding with ProRealTime™
//@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)
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
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 orangePlese convert VWAP TradingView strategy to ProRealTime
This topic contains 4 replies,
has 4 voices, and was last updated by JS
7 months, 3 weeks ago.
| Forum: | ProBuilder: Indicators & Custom Tools |
| Language: | English |
| Started: | 07/26/2025 |
| Status: | Active |
| Attachments: | 3 files |
The information collected on this form is stored in a computer file by ProRealCode to create and access your ProRealCode profile. This data is kept in a secure database for the duration of the member's membership. They will be kept as long as you use our services and will be automatically deleted after 3 years of inactivity. Your personal data is used to create your private profile on ProRealCode. This data is maintained by SAS ProRealCode, 407 rue Freycinet, 59151 Arleux, France. If you subscribe to our newsletters, your email address is provided to our service provider "MailChimp" located in the United States, with whom we have signed a confidentiality agreement. This company is also compliant with the EU/Swiss Privacy Shield, and the GDPR. For any request for correction or deletion concerning your data, you can directly contact the ProRealCode team by email at privacy@prorealcode.com If you would like to lodge a complaint regarding the use of your personal data, you can contact your data protection supervisory authority.