pine-scriptversionpine-script-v5

EMA Cross Strategy Does Not Work In Pinescript Version 6


Using the script below, I changed the version from '5' to '6' and it no longer works. Applied to QQQ for testing. Contacted TradingView and they said there are no errors but it clearly does not work. Pictures attached.

Script:

strategy('V6 EMA Crossover Strategy', pyramiding = 1, overlay = true,     initial_capital = 100000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, currency = currency.USD, commission_type = strategy.commission.cash_per_order, commission_value = 0, calc_on_every_tick=true)

Define EMA variables
fastEMA = ta.ema(close, 12)  // Fast EMA (12-period)
slowEMA = ta.ema(close, 200) // Slow EMA (200-period)

// Detect EMA crossover
longCondition = ta.crossover(fastEMA, slowEMA) or (fastEMA > slowEMA and     fastEMA[1] <= slowEMA[1])
shortCondition = ta.crossover(slowEMA, fastEMA)
// Entry Logic
if longCondition and strategy.position_size == 0
    strategy.entry("EMA Crossover Long", strategy.long)
if shortCondition 
    strategy.close_all()
// Plot the EMAs for visualization
plot(fastEMA, color=color.blue, title="Fast EMA")
plot(slowEMA, color=color.red, title="Slow EMA") ```

[enter image description here](https://i.sstatic.net/rUVRNhuk.png)
[enter image description here](https://i.sstatic.net/fzlk5vP6.png)
[enter image description here](https://i.sstatic.net/mLbB6QYD.png)
[enter image description here](https://i.sstatic.net/TMOtTXkJ.png)

I expected to see results like version 5 in the pictures attached, but version 6 misses some of the crossovers and is not consistent. Researching the migration guide there should be no errors in the script, so I am looking for help if I missed something or need to report a bug in Version 6. 

Solution

  • If you want to replicate the same v5 behavior, you need to add margin_long=0, margin_short=0 to your strategy() call in your v6 strategy.

    Related migration change is explained here.

    Default margin percentage

    The default margin percentage for strategies is now 100.

    In v5, the default value of the margin_long and margin_short parameters is 0, which means that the strategy does not check its available funds before creating or managing orders. It can create orders that require more money than is available, and will not close short orders even when they lose more money than available to the strategy.

    In Pine v6, the default margin percentage is 100. The strategy does not open entries that require more money than is available, and short orders are margin called if too much money is lost.