Probabilities Module - The Quant Science 
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © thequantscience

//@version=5
indicator(title = "Probabilities")

// ENTRY AND EXIT CONDITION 
entry_condition   = close > open // Replace with your entry condition 
TPcondition_exit  = close < open // Replace with your take profit condition 
SLcondition_exit  = ta.roc(close, 1) > 0.10 // Replace with your stop loss condition 

// LOOKBACK PERIOD 
look = input.int(defval = 30, minval = 0, maxval = 500, title = "Lookback period")

// LOGIC 
Probabilities(lookback) =>

    isActiveLong = false
    isActiveLong := nz(isActiveLong[1], false)
    isSellLong = false
    isSellLong := nz(isSellLong[1], false)

	int positive_results = 0
	int negative_results = 0

	float positive_percentage_probabilities = 0 
	float negative_percentage_probabilities = 0 

	LONG = not isActiveLong and entry_condition == true 
    CLOSE_LONG_SL = not isSellLong and SLcondition_exit == true
	CLOSE_LONG_TP = not isSellLong and TPcondition_exit == true

	for i = 1 to lookback

		if (LONG[i])
			isActiveLong := true
			isSellLong := false

		if (CLOSE_LONG_TP[i])
			isActiveLong := false
			isSellLong := true
			positive_results += 1

        if (CLOSE_LONG_SL[i])
	        isActiveLong := false
			isSellLong := true
            negative_results += 1

		positive_relative_probabilities = positive_results / lookback
		negative_relative_probabilities = negative_results / lookback
		positive_percentage_probabilities := positive_relative_probabilities * 100
		negative_percentage_probabilities := negative_relative_probabilities * 100

	positive_percentage_probabilities
	
probabilities = Probabilities(look) 

plot(probabilities, color = color.aqua)
