Hello Jing,
Thank you very much for your time, code example and expertise: this is very much appreciated.
You explained to me how to liquidate an option contract before expiration and how to verify its strike price relative to the underlying price.
What I'd ideally want to achieve now is to liquidate the option contract at the worst possible moment: out of all the prices the underlying will touch, I'd like to identify the one which is further away from the option strike and liquidate it that day. Can you kindly confirm to me there is no way to do this automatically? I think I can code it myself if there's not: maybe it'll be useful to other people as well (LEAN engine's assumptions that american options are always liquidated at expiry might show some strategies to be performing better than what they'd do in the real market, where options might be assigned, for the better or for the worse, before they expire).
The only problem in coding something like this is that the OnData() function only looks at a single tick values: we can't possibly check the future or the past in there (nor we want to - we'd be searching every tick for something we only need once: the liquidation date according to the "worst possible" idea).
If I might ask: what do you think would be the best way to code something like this? I'm not asking for specific code examples, just a general "best practice" idea. I was thinking about a function that gets called every time we sell an option: the function would need the option strike and the underlying prices for the period before expiration, and would return either nothing or a flag that indicates when the market will assign the option. The result of this function should be stored in a global variable and OnData will always check this variable and call .Liquidate based on what's stored in it (we could use a date, or the underlying price).
Thanks again for your input!
Joseph.