Comment on Managing your Script
If you think that EMA crossover for exit is too late as you have mentioned, you can have a separate exit strategy.
Typically an EMA crossover will make you a lot of money on days when the market is moving up and down quite a bit, otherwise it might be choppy..
So you can think of some other condition to exit, if you let me know the condition, i can help you with the code.