Code to protect the profits

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. Can anyone guide in this matter.

did you get the solution yet?

have you tried scaleout?