Hello all -- First of all thank you for reading this post, and any feedback you provide will add value. I'm needing a little help with an algo I'm working on. It is a intraday SPY options trading strategy that's based on the EMAs for SPY itself and other factors. In my current write up, I'm trying to achieve the following:

- 26 EMA < 97 EMA for SPY, and price of SPY is within 0.05 of the 26EMA (and if the slope of the 15EMA is negative, which I've yet to figure out), buy nearest ATM put and expiration and set a trailing stop. 

- I will be doing this for calls as well, but trying to get one side of the equation done first. 

It looks like the algo is buying puts when the conditions are satisfied, but it's not getting the nearest expiration; and at some point, I'm getting an index filter error, I assume its due to my conditions for the optionschain, but unsure how to resolve it. 

Also, I'm struggling a little with figuring out trailing stops for the options. I ended up setting a condition where it automatically liquidates when spy closes below the previous highest price, for profit; or if spy loses 20 cents below the 26EMA for some profit; or if spy closes above the 26EMA for a loss. 

Any thoughts on how to set a trailign stop for options, and how to getrid of this index filter error is greatly appreciated.

Thank you