pine script - Last entry never taken when pyramiding - Stack Overflow

admin2025-04-15  3

I tried some very simple code to us Pyramiding. I have 1000 capital. I want to take 4 entries maximum. So I plit the capital in 4. Then I run my code to take the positions. The first position is ok. Then 2 positions are also ok. But the last one never happens, even if conditions are met.

I tried to reduce my capital using 95% of my inital capital (thinking that it could be a round problem). Same result.

I tried to force another value for the last entry only. If i use 50% of the remaining capital, sometimes it works.

I also tried in version 6 of Pine script. Same problem.

Any idea?

Here is a simple version of my code:

//@version=5
strategy("Multi-Entry Strategy", overlay=true, initial_capital=1000, default_qty_type=strategy.fixed, default_qty_value=250, pyramiding=4)

// Calculate EMAs 
ema10 = ta.ema(close, 10)
ema20 = ta.ema(close, 20)

// Signal for first entry: EMA10 crossing above EMA20
entrySignal = ta.crossover(ema10, ema20)

// Persist variables for tracking entries
var int entryCount = 0
var float lastEntryPrice = na

// First entry: when not in position and signal is true
if (strategy.position_size == 0 and entrySignal)
    strategy.entry("Long1", strategy.long)
    entryCount := 1
    lastEntryPrice := close

// Additional entries: add if price crosses under 2% below the last entry price, up to 4 entries total
if (strategy.position_size > 0 and entryCount < 4)
    threshold = lastEntryPrice * 0.99
    if (ta.crossunder(close, threshold))
        strategy.entry("Long" + str.tostring(entryCount + 1), strategy.long)
        entryCount += 1
        lastEntryPrice := close

// Exit: close all positions if price is 2% above the average entry price
if (strategy.position_size > 0 and close > strategy.position_avg_price * 1.02)
    strategy.close("Long1")
    strategy.close("Long2")
    strategy.close("Long3")
    strategy.close("Long4")
    entryCount := 0
    lastEntryPrice := na

plot(ema10, color=color.blue)
plot(ema20, color=color.orange)

Thank you for you help.

转载请注明原文地址:http://www.anycun.com/QandA/1744730436a86816.html