How to Calculate the Number of Bars from Buy / Short signal

Dear Rajendran,
Can u help me with the below mentioned issue:
I have a profitable strategy but the issue with it is it leaves a lot of earned profits, I need support to write a code that if a threshold percent profit (say 10%) is hit then exit if a certain percent (say 40%) of the maximum potential profit (buy price - the highest high after the buy signal) is lost.
I have tried Applystop, barsince, highestsince, looping but was unable to get the desired result.