Hi all! I would really appreciate your help with the following:

I have obtained buy signals from stock data close prices for every 5 minutes. If a buy signal is triggered, I want to retrieve a sell signal 4 periods later and ignore the signals in between (if at t=4 the signal is "BUY" it needs to be "SELL"). If after the sell signal directly the buy signal still holds, there should be a buy signal again and after 4 periods a sell signal etc. If directly after the buy signal there is (e.g. for a few periods) no buy signal I would want the next buy signal and then 4 periods after the sell signal etc. I have tried using the generate/replace commands, but that sadly doesn't work all the time (still some errors). Is there another way to do this? In addition, if I would want the buy signal to hold for 3 periods before the buy signal is triggered, how does that change the code?

Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input double CLOSE str3 buy_signal
4346.03 ""
4344.01 ""
4360 "BUY"
4377.84 "BUY"
4377.59 "BUY"
4340.01 ""
4345.31 "BUY"
4354.9 "BUY"
4340 ""
4340 ""
4340 ""
4345.95 "BUY"
4337 ""
4320.07 ""
4344.95 "BUY"
4320.03 ""
4320.01 ""
4320 ""
4318.51 ""
4325 "BUY"
end

Below shows an example how I suppose it would look like with the correct signals (after "//")
Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input double CLOSE str3 buy_signal
4346.03 ""
4344.01 ""
4360 "BUY" // "BUY"
4377.84 "BUY"
4377.59 "BUY"
4340.01 ""
4345.31 "BUY" // "SELL"
4354.9 "BUY" // "BUY"
4340 ""
4340 ""
4340 ""
4345.95 "BUY" // "SELL"
4337 ""
4320.07 ""
4344.95 "BUY" // "BUY"
4320.03 ""
4320.01 ""
4320 ""
4318.51 "" // "SELL"
4325 "BUY" // "BUY"
end

Thank you in advance!