Will my limit order be filled ?
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mks17

//@version=5
indicator("Will my order be filled ?")

limitMargin = input.float(0.2, "Margin % from last close", step=0.01) / 100
numberBars = input.int(5, "Number of Bars to have a fill")
sourceL = input.source(close, "Source for the Long fill")
sourceS = input.source(close, "Source for the Short fill")

checkEntryL(int j) =>
    counter = 0
    for i = 0 to j - 1
        if sourceL[i] < close[j] * (1 - limitMargin)
            counter := 1
            break
    counter

checkEntryS(int j) =>
    counter = 0
    for i = 0 to j - 1
        if sourceS[i] > close[j] * (1 + limitMargin)
            counter := 1
            break
    counter

resultL = 0, resultS = 0
for i = 1 to numberBars
    checkL = checkEntryL(i)
    resultL := resultL + checkL
    checkS = checkEntryS(i)
    resultS := resultS + checkS


PercFilledL = resultL * 100 / numberBars
PercFilledS = resultS * 100 / numberBars

f_fhma(float _src) =>
    sum = 0.0, var counter = 0
    sum := nz(sum[1])
    if not(na(_src))
        counter := nz(counter[1]) + 1
    sum := nz(_src) + sum
    fhma = sum / counter
    fhma

avgL = f_fhma(PercFilledL)
avgS = f_fhma(PercFilledS)

// plot(PercFilledL, "Percentage of Long limit orders Filled")  
// plot(PercFilledS, "Percentage of Short limit orders Filled")      
plot(avgL, "Percentage of Long limit orders Filled", color=color.blue)
plot(avgS, "Percentage of Short limit orders Filled", color=color.red)


