请求协助修复Pine Script V4策略报错及代码转换问题
Hey there, let's tackle your TVI strategy issues step by step. I've worked through the problems you mentioned with EUR/USD errors and converting lines 115-116 to Pine Script V4, here's what I came up with:
1. Fixing EUR/USD Study Error
The error on EUR/USD likely stems from two key issues: invalid initial values for stop levels and potential division by na (not available) values when calculating position size—this is more common in forex pairs due to their price structure and syminfo properties. Here's how to fix it:
Key Modifications:
- Stop Level Initialization: Replace the initial
0.0value forlongStopandshortStopwithna—a0.0stop price is unrealistic for forex pairs and can trigger invalid order errors. - Position Size Safety Checks: Add guards to handle
navalues in risk calculations and ensure position size is always at least 1 (valid for strategy orders).
Here's the updated code snippet for these sections:
// Step 4) Determine long trading conditions enterLong = eLong and tradeWindow longStop = na // Initialize with na instead of 0.0 longStop := enterLong ? close - (stopOffset * atrValue) : longStop[1] // Step 5) Code short trading conditions enterShort = eShort and tradeWindow shortStop = na // Initialize with na instead of 0.0 shortStop := enterShort ? close + (stopOffset * atrValue) : shortStop[1] // Calculate position size riskEquity = (maxRisk * 0.01) * strategy.equity riskTrade = stopValue * syminfo.pointvalue // Handle na values to avoid division errors riskTrade := na(riskTrade) ? 1 : riskTrade maxPos = ((maxExposure * 0.01) * strategy.equity) / ((marginPerc * 0.01) * (close * syminfo.pointvalue)) maxPos := na(maxPos) ? 1 : maxPos // Ensure position size is at least 1 and an integer posSize = usePosSize ? max(1, floor(min(riskEquity / riskTrade, maxPos))) : 1
2. Converting Lines 115-116 to Pine Script V4
The original commented lines use Pine Script V3 syntax for plotting stop levels. In V4, the plot() function's style parameter uses enum values instead of shape.circle. Additionally, using plotshape() is more intuitive for marking stop levels as discrete points. Here are two options:
Option 1: Using plot() (Line with Circle Markers)
This keeps the line-based approach but updates the style to V4 standards:
plot(series=strategy.position_size > 0 ? longStop : na, color=color.green, linewidth=2, style=plot.style_circles, title="Long Stop") plot(series=strategy.position_size < 0 ? shortStop : na, color=color.red, linewidth=2, style=plot.style_circles, title="Short Stop")
Option 2: Using plotshape() (Discrete Circle Shapes)
This is more visible and aligns with your existing signal markers:
plotshape(series=strategy.position_size > 0 ? longStop : na, style=shape.circle, color=color.green, location=location.absolute, size=size.small, title="Long Stop") plotshape(series=strategy.position_size < 0 ? shortStop : na, style=shape.circle, color=color.red, location=location.absolute, size=size.small, title="Short Stop")
Full Updated Strategy Code
Here's the complete modified code incorporating both fixes:
//@version=4 // Step 1) Define strategy settings strategy(title='Yotyord - TVI', overlay=false, pyramiding=0, initial_capital=100000, commission_type=strategy.commission.cash_per_contract, commission_value=25, slippage=2) //Session Input Options smooth = input(title='Signal Smoothness, (<0 to hide):', type=input.integer, defval=4) length = input(10,title='Highest High Volume') // Position sizing inputs usePosSize = input(title="Use Position Sizing?", type=input.bool, defval=true) maxRisk = input(title="Max Position Risk %", type=input.float, defval=2, step=.25) maxExposure = input(title="Max Position Exposure %", type=input.float, defval=10, step=1) marginPerc = input(title="Margin %", type=input.integer, defval=10) // Stop inputs atrLen = input(title="ATR Length", type=input.integer, defval=10) stopOffset = input(title="Stop Offset Multiple", type=input.float, defval=4, step=.25) // Step 2) Calculate strategy values //Writing Trade Volume Index graph (TVI) f_tvi()=> float _direction = na float _return_tvi = na _min_tick=syminfo.mintick _price_change = close - open if _price_change > _min_tick _direction :=1 if _price_change < -_min_tick _direction :=-1 if abs(_price_change) <= _min_tick _direction :=_direction[1] if na(_return_tvi[1]) _return_tvi := volume else if _direction > 0 _return_tvi := _return_tvi[1] + volume else if _direction < 0 _return_tvi := _return_tvi[1] - volume else _return_tvi[1] TVI=f_tvi() tradeWindow = time <= timenow - (86400000 * 3) stopValue = atr(atrLen) * stopOffset //Get ATR Values atrValue = atr(atrLen) // Calculate position size riskEquity = (maxRisk * 0.01) * strategy.equity riskTrade = stopValue * syminfo.pointvalue // Handle na values to avoid division errors riskTrade := na(riskTrade) ? 1 : riskTrade maxPos = ((maxExposure * 0.01) * strategy.equity) / ((marginPerc * 0.01) * (close * syminfo.pointvalue)) maxPos := na(maxPos) ? 1 : maxPos // Ensure position size is at least 1 and an integer posSize = usePosSize ? max(1, floor(min(riskEquity / riskTrade, maxPos))) : 1 //Buy when TVI = HHV and Sell When TVI = LLV hhV = highest(TVI,length) llV = lowest(TVI,length) BuySig = hhV == TVI ? hhV : na SellSig = llV == TVI ? llV : na eLong = hhV == TVI eShort = llV == TVI plotshape(BuySig, style=shape.circle,title = "Buy Signal",color = color.green,location=location.absolute) plotshape(SellSig, style=shape.circle,title = "Sell Signal",color = color.red,location=location.absolute) // Step 3) Output strategy data plot(TVI,color=color.white,title='TVI') plot(hhV , color=color.green, title="HHV") plot(llV , color=color.red, title="LLV") // Step 4) Determine long trading conditions enterLong = eLong and tradeWindow longStop = na // Initialize with na instead of 0.0 longStop := enterLong ? close - (stopOffset * atrValue) : longStop[1] // Step 5) Code short trading conditions enterShort = eShort and tradeWindow plotshape(enterLong, style=shape.circle, title = "Enter Long", location = location.belowbar, color = color.green) plotshape(enterShort, style=shape.circle, title = "Enter Short", location=location.abovebar, color = color.red) shortStop = na // Initialize with na instead of 0.0 shortStop := enterShort ? close + (stopOffset * atrValue) : shortStop[1] // Updated stop level plotting (Option 2 used here) plotshape(series=strategy.position_size > 0 ? longStop : na, style=shape.circle, color=color.green, location=location.absolute, size=size.small, title="Long Stop") plotshape(series=strategy.position_size < 0 ? shortStop : na, style=shape.circle, color=color.red, location=location.absolute, size=size.small, title="Short Stop") // Step 6) Submit entry orders if (enterLong) strategy.entry(id="EL", long=true,qty=posSize) if (enterShort) strategy.entry(id="ES", long=false,qty=posSize) // Step 7) Send exit orders if (strategy.position_size > 0) strategy.exit(id="XL", from_entry="EL", stop=longStop) if (strategy.position_size < 0) strategy.exit(id="XS", from_entry="ES", stop=shortStop) strategy.close_all(when=not tradeWindow)
内容的提问来源于stack exchange,提问作者Pete

