Your code seems OK (although I have not tested it) except for the fact that the IF NOT ONMARKET will mean that a reverse signal will not close a trade and open one in the opposite direction. Perhaps this is what you want and there is some more code that you have not shared with us?
Also how often does close cross over the two indicators at exactly the same bar?
You should try using GRAPH to check the values of the two indicators compared to close