Code for "nearest term ATM call option"
Look for nearest term ATM call option prior to buy to open.
Buy To Open when EMA 10 is above the EMA 30
Sell To Close when EMA 10 is below the EMA 30
Underlying: SPY (or any other)
Call Option: Look for ITM option (closest to 50 deta) with the closest strike price, no hold overnight.
How would I code that ?
Size:
Color:
QUOTE:
Call Option: Look for ITM option (closest to 50 deta) with the closest strike price, no hold overnight.
This is going to be a tough nut to crack. Programming the rest is trivial.
Wealth-Lab constructs synthetic option contracts based on the underlying stock price and the Black-Scholes model. Without going out of your way, you basically cannot look up an option because it does not exist as an entity in your DataSet.
Of course it's possible to look up the desired call option ticker on Fidelity's website and add that to a DataSet but this would only make sense if they provide its historical data in WLP (I'm not sure if they do). If you know the ticker the data is available in WLP, things get easy again.
Size:
Color:
OK,
I think I understand what you are saying. I simply need the ticker data available in WLP. I don't know because I wen't to finance.yahoo.com to find this example. Then I asked Fidelity chat how to put that into a chart and they gave it to me.
Example
Underlying Symbol: SPY
Expiry: Dec 21, 2018
Instrument: A Call Option
Strike Price: 216
-SPY 18 12 21 C 216 - here it is broken out into yr/mo/day/call/strike
-SPY181221C216 - If I put this into a chart in WLP, I get data.
Size:
Color:
Good to know. With -SPY181221C216 and SPY in one of your DataSets, give this a try:
CODE:
Please log in to see this code.
Size:
Color:
Thank you for that. I'm new to the platform, so how would I test that?
I don't know where to put it in or how to do it exactly?
Size:
Color:
Size:
Color:
Hi Eugene,
Thank you very much for your assistance!!
I'm stuck on the purpose of the code you provided, as it appears to be targeting -SPY181221C216 instead of figuring out what that is.
I do see that the "ticker is available in WLP" where you said "things get easy again". This is true for the underlying SPY, and also for individual options such as -SPY181221C216.
Based on the fact that the ticker is available, how would I specify for instance "nearest term ATM call option" on another chosen underlying chosen at the time of code execution?
Size:
Color:
Hi Ted,
This code was an example, and you're looking for a full-fledged solution without having disclosed all the rules. Solution's complexity depends on how is "-SPY181221C216" defined. Looks like you're after doing it automatically.
If so, to specify "nearest term ATM call option" for a given stock first you'd have to come up with clear rules in plain English. This is required to create a WealthScript Strategy. The "-SPY 18 12 21 C" part is that I understand, and could code considering that this must be the first Friday of a month. It's the strike price definition algorith, that is unclear.
Size:
Color:
Yep, that appears to be the challenge. How would I come up with the appropriate strike price based on the rule "use the nearest term ATM monthly call option". If I had a way to look that up in an algorithmic fashion, that would be fantastic!
1 approach might be to define differently and say "find the standard option with the least # of days to expiration, that is closest to a delta of 50"
Size:
Color:
Sorry, I'm not an options guy so "closest to a delta of 50" does not ring a bell to me. Is there a rule set (algorithm) for this or has this be looked up on some external resource (which would greatly complicate things)?
Size:
Color:
I tried running the code above for the first time, I received the run time error shown here
With respect to defining a "near month option", I found the following definition from investopedia.com:
In the context of options and futures, the month closest to delivery (futures) or expiration (options). "Nearby month" is sometimes referred to as "nearest month," "front month" or "spot month." A contract for the nearby month is the shortest contract that an investor can purchase. Trading is usually most active for the nearby month as compared to deferred months.
Nearby Month Definition | Investopedia
http://www.investopedia.com/terms/n/nearbymonth.asp#ixzz4Q0lOAYPJ
Size:
Color:
If you want a technician to have a look at screenshot, please attach it directly when replying. PNG preferred (JPEG is so so), under 3 MB. Thanks.
With regard to "nearby month" it's not clear to me why your first response had an example with expiry in 2018. Anyway, there's a built-in function in WealthScript that should help you:
NextOptionExpiryDate. Look it up in the QuickRef (F11 key). Here's an example:
CODE:
Please log in to see this code.
Size:
Color:
I think I understand.
Would you agree that we have resolved how to find the "nearest month" with NextOptionExpiryDate?
So next to resolve would be my reference in Post #8 to an "ATM call option".
ATM refers to an option which is "At The Money". Since "At The Money" changes over time, it's meaning is non-specific. An At The Money option is simply one that is half way between the In The Money options and the Out Of The Money options, hence the term delta ".50" abbreviated as delta 50.
Size:
Color:
Updated image. Unable to include in body but it did attach.
Size:
Color:
Thanks for clarifying it. So is ATM identical to the close price rounded up (down)?
Size:
Color:
Eugene, let me take a crack at it. I can see the WLP Option data, so this is pretty interesting.
.. but Delta isn't available, so as Eugene said, we can simply give you the ATM strike closest to the current price. We'll assume that it's the current price rounded down by a specified amount (0.5 in this case).
Size:
Color:
Thank you both. It looks like that would work.
Just to recap overall goal:
Underlying: SPY (or any other selected ticker)
Call Option: Look for nearest term, at-the-money option
Buy To Open when EMA 10 is above the EMA 30
Sell To Close when EMA 10 is below the EMA 30
Size:
Color:
1. Is the idea to trade the ATM option based on the EMA crossovers of the underlying?
2. You said "no hold overnight". What's the bar interval?
Anyway, before I get to that I'll show you what I've got. The script below produces the following image. The interesting thing is that the synthetic option prices closely follow the real option pricing, just not at the right level. But since it's the difference that matters in trading, this would be acceptable for a backtest.
Note that WLP's synthetic options will give you the correct dollar profit for trades in a backtest, but to do that for real option data, you need to set up option symbols in the Symbol Info Manager so that the multiplier (100) is correct. Otherwise, if you buy a call for $1 and sell it for $2, you make only $1, instead of $100.
Actually, using the Symbol Info Mgr is definitely feasible. We could probably come up with a single Regex that would work for practically all option symbols in the -SYMyyDDmmCstrike format.
And here's the script, which has 2 parameters:
1. Days out - the minimum days allowed for the next strike. Otherwise the next month's strike is chosen.
2. Round down.- this needs to be set correctly for the underlying. For example, you can use 0.5 for SPY, but not for CSCO.
CODE:
Please log in to see this code.
Size:
Color:
Cone and Eugene,
Thank you so much!!
I am still trying to get my head around what you are saying.
As for the code itself, my girlfriend and I are trying to do some Microsoft lessons together where we are writing our first code blocks in C# so I can get a feel for the syntax.
I can't wait to test your code at work tomorrow.
In answer to your question, this is how I am visualizing the 10/30 EMA cross. In my attached example, the blue line represents the short 10 period ema and the red line represents the longer 30 period EMA.
Size:
Color:
QUOTE:
In answer to your question, this is how I am visualizing the 10/30 EMA cross.
The crossover is pretty standard, you should find an example code in post #4. Question is what do you trade: the option or the underlying?
Size:
Color:
Setup: Perform each step carefully!1. Create this entry in the Symbol Info Manager (Ctrl+Alt+F). Here's the "symbol" to copy and paste there:
-[A-Z]{1,5}\d{6}[PC][0-9]+\.?[0-9]. Select the other fields as shown here:
2. Install the
Community.Components Extension (click) if you haven't already.
3. Set your commissions for trading in Preferences (F12) > Commissions. I think Fidelity charges $7.95 per trade plus $0.75 per contract, so if you're just trading 1 contract you could use a $8.70 Per Trade commission. (For multiple contracts, we'd have to create a new Commission add-in.)
4. Open a new Strategy Window (Ctrl+Shift+S), copy, paste, and save this code.
4a. Click the
Compile button at the top of the editor. (Always do this after changing the code in the editor.)
CODE:
Please log in to see this code.
5. Make sure that File > Update Data On-Demand is Checked.
6. Click on SPY in a 1-minute (or any intraday) DataSet.
7. Important! You can't ask for too much data because it appears that you can only request current contracts. So make sure that the Data Range starts from approximately the last expiry date. I also suggest using 1 Share Raw Profit sizing for testing.
If you run the script and see this message, it's because you requested data for a contract that doesn't exist (or for which there is no data). You can try to fix this by bumping up the start date, or, try using different contract rounding, like "1" instead of "0.5" in the Strategy Parameters.
CODE:
Please log in to see this code.
8. Give it some time to collect data the first time you Execute it. If everything goes well, you'll get something that looks like this. (This was run on 1-Minute SPY starting Nov 7, 2016
Size:
Color:
Okay, but note that although you can backtest options using WLPro, you cannot trade (or auto-trade) option contracts using WLPro, WLPro would be able to give you an Alert when to buy a contract, but you'd have to place the trade with AT Pro or at fidelity.com.
Size:
Color:
Nice.
But for me it works only, if I use 5 as a rounding. I know that option contracts in multiple of 5 are most liquid one.
For all lower "rounding" including "1", I get "Invalid Benchmark Buy and Hold Symbol" for some options.
For example using "1" as rounding and 6 months.
No option data for -SPY161216C218
No option data for -SPY160916C217
and Nothing works for VXX. It always produce "No options data for xxx"
Suggestion: Use of other optionable symbols may help to refine the code
Size:
Color:
@Harapa.
The first thing I wrote in Post #21: Setup: Perform each step carefully!
Specificaly, see step 7, where it says "Important!".
(6 months is too far back.)
Also, if you don't get data for a current, non-expired option symbol like -SPY161216C218 that you know has been traded, try typing it into a chart window. It works for me, so it must for you too.
Size:
Color:
Cone, thanks for the comment about 6 mos being too far back. I'm still trying to get access to the extensions but one thing I think might be useful for back-testing is to set the data request to 100 trades as opposed to time since 100 is commonly referred to as enough data to see if a system might be viable.
Size:
Color:
Here's the thing. You can't get the data for expired contracts. That's why if you want to use this technique, you must start from the last contract's expiration.
If you want to go back further, you need to test using Synthetic Option contracts. The code I posted in Post #18 above compares Synthetic and "real" options. You can see that synthetic options are more liquid and aren't necessarily priced accurately, but they approximate the movements of a live contract fairly well on an intraday basis. Anyway, you can test both ways with a current contract and see how much the results differ.
For more on Synthetic contracts, see Help > WealthScript Programming Guide > Programming Trading Strategies > Options Strategies
Size:
Color:
Ok, great. That makes sense.
I spoke too soon on the errors also. The code runs for me now.
Size:
Color:
QUOTE:
@Harapa.
The first thing I wrote in Post #21: Setup: Perform each step carefully!
Specificaly, see step 7, where it says "Important!".
(6 months is too far back.)
Not a case of reading dyslexia...
6 moth was extended following suggested solution (in an attempt to make the script work). "Position sizing" is not the culprit.
QUOTE:
You can try to fix this by bumping up the start date, or,
Same issue seen even with 1 month data. Of course flagged contract doesn't have any data. But this rendered the whole script useless as there is no way to purge this contract.
Size:
Color:
Re: -VXX1111830
This contract expired last week. If the data aren't available, you need to use Synthetic Contracts.
Here's a version of the script for SyntheticOptions only. You should have better luck with this, and you can use as much history as you like.
CODE:
Please log in to see this code.
Size:
Color:
Hi Cone, thank you for the revised code with the ability to use more data with synthetic options.
I made a video of my own representation of this and am a little confused on how to get it to display the way I had hoped to see it.
Here is my screencast
http://screencast.com/t/gQm0i1fDvh
Size:
Color:
There is no need in using external sites for posting screenshots. As you could see there's convenient linklabel "Add Attachments" (next to the "Post" button) that lets you attach multiple images straight to your response. PNG format is preferred, MS Paint (comes with any Windows) will do it.
Size:
Color:
Hi Eugene,
I think he used Camtasia Studio, where a screencast is a convenient publishing option. I like it. I'll respond with my own.
Size:
Color:
Size:
Color:
That's really nice Cone. Thank you for the video. That really helps me to understand what is happening. I'm nowhere near developing an adequate strategy yet for short-term trading but this definitely helps get me started!
Size:
Color:
Why do the panes above the chart exist?
I'm not sure I understand the point as it makes the chart very difficult to read.
Size:
Color:
The code creates a new pane for each option contract traded. The video shows a way to eliminate the panes, and it's included in the code above - just uncomment (remove the //) from line 131, return; (and don't forget to compile).
Size:
Color:
Got it. that got rid of the panes and left the chart. I'm not seeing where the orders are though on the chart. What am I missing?
Size:
Color:
You're missing the panes!
I'm certain I explained it in the video (please watch again), but if you want to see the trades on the chart, you need to plot the options. (Where else would the option trades be plotted?) If there are too many contracts, then reduce the data loaded (don't use All Data).
And to be crystal clear, now we're not backtesting using "live option data". These are simulated contracts based on Black-Scholes. Backtests with live data (if it were available) would certainly yield different (maybe better, maybe worse) results.
Tip:
Do yourself a favor and please maximize the Strategy window so that when you eventual chart the panes again, you'll have more room for them ;)
Size:
Color:
Cone thank you. I went back through this again and re-watched your video and I still don't see the markings on the chart, but I do see the trades.
Your assistance is greatly appreciated.
http://screencast.com/t/qmw9mDKz
Size:
Color:
So to "plot the options", you mean to say that the code doesn't do that?
Can you plot them without showing the pane using the return statement?
Size:
Color:
Delete the "return;" statement (or put two backslashes in from of it //), then hit the "Compile" button at the the of the editor, and then run again.
The "return" statement stops the code from executing anything below it, which is what plots the panes. Remember, we wanted to get rid of the panes when the script traded too many contracts.
Let's use a Strategy Parameter "switch" to turn on/off the plotting of the options and forget about that "return" nonsense. Here's another code replacement for that:
CODE:
Please log in to see this code.
Size:
Color:
Ok, great. Now I see your StrategyParmeter definitions at the top of the code. I also see the lines and orders on the chart, but also the panes which as you discussed in your video, makes the chart hard to read.
What I am wanting to do is to show all the plotting on the chart.
To me, and specific to this case, a plot means the EMA lines, as well as entry/exit signals and filled orders.
The panes are different.
I'm wanting the plot to show, but not the panes. Ideally, we could turn them individually on/off as desired.
The question regarding the pricing panes has been migrated to this location in order to keep it separate from the strategy itself
https://www.wealth-lab.com/Forum/Posts/Clear-panes-without-clearing-plots-38579/
Size:
Color:
I suppose that I don't understand what you want.
You see, if you want to see the trades on a chart, then you need to plot the options. Those have to be plotted in a different pane. Furthermore, since the strategy trades differently contracts, each contract needs a new pane, otherwise the prices would all run together.
Also, it doesn't make sense (to me) to put those trades in the underlying's (main) PricePane. Imagine you did that for AAPL. You'd have a chart that went from 1 to 115, and nothing in between.
If you could draw me a picture (or provide a link to an example) of what you want to see, maybe I could help more.
-----
Edit -
Maybe putting the prices of the synthetic contracts in the same pane isn't so bad. Here's a small change that might make a big difference. The only issue that you won't easily be able to identify the contract traded since all of them are in the same pane. Also, you'll see a big list of contracts on the left side of the chart. You can suppress that display by clicking the first button after the word "Show:" in the Function Toolbar.
CODE:
Please log in to see this code.
Size:
Color:
Ok, here you go
Thanks for your help very much.
Size:
Color:
If you look in the lower left corner at the Strategy Parameters, you can toggle off all of those panes by clicking on the left side of the "Plot Options" slider to make it "0".
Also, try the last version of code in post #43.
1. It Plots all the options in the same pane. Doing it this way, you can't easily tell match a contract to a series.
2. I just realized that the PlotSymbolTrades() routine internal uses PlotSymbol(), so I removed it.
Normally you can double click a trade in the Trades view to see that trade approximately centered in the Chart view. That doesn't work in this case because these synthetic option symbols cannot be found in the DataSet.. Consequently to see specific trade, just look at the entry/exit times and scroll the chart manually.
Size:
Color:
Thank you again,
I commented out the line you mentioned
CODE:
Please log in to see this code.
Now changing to one in the parameters for PlotOptions doesn't seem to have any effect. Now there are no panes but also no orders on the chart where I would expect to see them. I do however still see plot lines on the chart for the EMA as well as individual trades.
I'm using the 1 minute bars and a time frame of 2 weeks.
Assistance still needed in getting the actual orders to show on the chart itself, but without the price panes.
Size:
Color:
1. There's no way to show the orders on the chart without showing the options series in those panes.
2. Please use the code in post #43 and forget about everything before. After you paste, compile, and run it, you can turn the option pane on and off by clicking on the left/right side of the "Plot Options" slider parameter in the lower left corner of Wealth-Lab.
I sure hope this image helps you understand what I'm saying - (click the image for a full resolution view)
Size:
Color:
I see said the blind man. Of'course it can't show the trades on the chart of the underlying because the underlying isn't what we are buying and selling.
Can you further explain the shaded areas that are pointed out there?
Size:
Color:
... as he picked up his hammer and saw. ;)
When a crossover is detected, the code shades the background using the statements SetBackgroundColor() or SetPaneBackgroundColor(). We don't have to do that, but it allows you to easily see the "signal bar". The trades occur on the next bar, e.g., BuyAtMarket(bar + 1).
Size:
Color:
Yes, that's fantastic!
I do notice that the red shading (indicating an sell to close) doesn't go all the way up where the green shading (indicating buy to open) seems to.
I have placed my own recap of the logic where it appears to be used at line 106-109. What would you add to that?
Buy To Open nearest term ATM (at-the-money) call option when EMA 10 is above the EMA 30
Sell To Close ATM call option when EMA 10 is below the EMA 30
CODE:
Please log in to see this code.
Size:
Color:
QUOTE:
I have placed my own recap of the logic where it appears to be used at line 106-109. What would you add to that?
This is what the strategy does using "CrossOver and CrossUnder" signals in the block of code after line 109.
As I explained in post #49, the shading is done by SetBackgroundColor() (colors all panes) or SetPaneBackgroundColor() (colors the specified pane). If you want the shading to got all the way up, just modify the code by replacing SetPaneBackgroundColor with SetBackgroundColor, but pay attention to the difference in syntax.
Size:
Color:
I see.
I get an error when I change SetPaneBackgroundColor to SetBackgroundColor.
http://screencast.com/t/1EKOyTvFII see now what I did wrong though and removed the PricePane syntax from the parameters.
Now all is good!
This thing actually 'looks' profitable on a back-test
Amazing!
Size:
Color:
Perfect. Now if we wanted to play both buy sides, buying and selling calls and puts one-at-a-time
Sell To Close nearest term ATM put option AND Buy To Open nearest term ATM (at-the-money) call option when EMA 10 is above the EMA 30
Sell To Close nearest term ATM call option AND Buy to Open nearest term ATM put option when EMA 10 is below the EMA 30
Exit all positions at market on End-Of-Day
How are commissions figured in?
How is slippage figured in?
Size:
Color:
QUOTE:
How are commissions figured in?
Enable and configure your trade commissions in Preferences (F12) > Commissions
QUOTE:
How is slippage figured in?
Enable and configure in Slippage and Round Lots. With the dialog in focus, press F1 for more information in the User Guide.
QUOTE:
Exit all positions at market on End-Of-Day
This and the previous strategy exits on the Close on the last bar of the day. Note that you will not get an alert for that order. AtClose Alerts are not supported for live orders.
This my last Christmas present to you for this year!... Basically the same strategy with a little re-arranging.
CODE:
Please log in to see this code.
Size:
Color:
This is really nice! Thanks again Cone.
I have expanded the rules to include some time where we won't be in a position at all.
The way this would be traded is to look at an online screener or watchlist like the screener here at fidelity.com
https://research2.fidelity.com/pi/stock-screener, decide what to launch this short term trade on, and then execute it.
Can you assist with incorporating these new rules?
Thanks for the super good comments!!
LE Condition - Buy the nearest term ATM (at-the money) call option at market when:
The EMA 10 has crossed above the EMA 30
AND
The MACD histogram is positive
AND
It is during regular market hours.
LX Condition - Sell open call contract at market when:
The EMA 10 has crossed below the EMA 30
OR
The MACD histogram is negative
OR
The RSI is at 80 or above
OR
It is one minute before the end of the trading day.
SE Condition - Buy the nearest term ATM (at-the money) put option at market when:
The EMA 10 has crossed below the EMA 30
AND
The MACD histogram is negative
AND
It is during regular market hours.
SX Condition - Sell open put contract at market when:
The EMA 10 has crossed above the EMA 30
OR
The MACD histogram is positive
OR
The RSI is at 20 or below
OR
IT is one minute before the end of the trading day.
Size:
Color:
This code should find and trade the EMA 10/30 cross against the nearest term at-the-money option for any underlying that is dragged into the chart. It should be out of the trade by the end of the day with no overnight hold ability.
The entry when the EMA 10 has crossed above 30 appears to be coded.
The exit when the EMA 10 has crossed back below 30 now appears to be there also.
Cone did the original code did an amazing job!
If possible I would like some assistance in the comments so that I can better follow what this particular code is doing.
Assistance in the continuation of this effort is greatly appreciated.
I'm not looking to do any short entries or short exits.
It says to round strikes to 5 where it should be 1/2 or .5.
If .5 is not available, then it should round to 1 strike. If 1 strike is not available, then it should round to five.
It should not exit on a different strike price than it entered on.
The other problem is that I see both call and put option codes where I would expect to see calls only or puts only depending on what is chosen for a given day trade.
The strategy should not hold overnight and it should be very clear where the day started and where it ended, and how many trades were executed for that day.
Size:
Color:
I'm time constrained for the next couple days, but let's answer a few of these:
QUOTE:
It says to round strikes to 5 where it should be 1/2 or .5.
Choose your desired rounding using the "Round strike" StrategyParameter. The code above allows changes in $1 increments. To make it 0.5 increments, change this line of code -
CODE:
Please log in to see this code.
QUOTE:
The other problem is that I see both call and put option codes
The code buys puts when the fast EMA crosses under the slow EMA, and buys calls for a cross over. If you expect something different, then we need different rules.
QUOTE:
The strategy should not hold overnight...
The strategy does indeed exit any open position on the last bar of the day.
Size:
Color:
Thanks for all the hand holding here, and great clarity on what the code is currently designed to do.
I knew I was seeing something weird but could not see where to make the changes.
For the rules, I was wanting to use the EMA 10/30 cross with buying a call when EMA 10 has crossed above the EMA 30 and selling the call when the EMA 10 has crossed below the EMA 30. No short entry or short exit required.
Ideally, the trades would not occur at market price, but rather a limit order at the mid price.
At the end of the day, the same thing with the mid price.
If no fill, then it just sits there till it can get filled at the mid price or tries again to exit at the mid price at the end of the day.
I understand that Wealth Lab Pro is just for back-testing, and that live testing via paper money or otherwise does not exist.
Given that hurdle, are there any suggestions regarding how I might trade it against a real money account?
How do I account for commissions in the back-testing? What values?
How do I account for slippage in the back-testing? What values?
Are there other components that I should account for in back-testing? What values?
Size:
Color:
QUOTE:
I understand that Wealth Lab Pro is just for back-testing
Just to be clear, you can trade stocks live with WL Pro.
QUOTE:
...are there any suggestions regarding how I might trade [options] against a real money account?
You can be alerted by sound and/or email to place the order in AT Pro.
QUOTE:
How do I account for commissions in the back-testing? What values?
Preferences (F12) > Commissions. Click Per Share Commissions > Commission Settings and enter the value for 1 contract.
QUOTE:
How do I account for slippage in the back-testing? What values?
Preferences (F12) > Slippage and Round Lots. Then hit F1 for User Guide discussion, especially for Limit Order slippage.
QUOTE:
Are there other components that I should account for in back-testing? What values?
Data. Also see Preferences (F12) > Backtest Settings
I'll get back to you on the strategy changes.
Size:
Color:
QUOTE:
Ideally, the trades would not occur at market price, but rather a limit order at the mid price.
Define "mid price"
QUOTE:
If no fill, then it just sits there till it can get filled at the mid price or tries again to exit at the mid price at the end of the day.
What should happen if you can't exit at the mid-price on the last bar of the day?
Size:
Color:
Mid price would be the price between the bid and the ask. Some platforms call it mid price. Thinkorswim calls it the mark price.
Last bar of the day should check for exit at the mid-price but exit at market if not found.
Size:
Color:
Unless you provide bid/ask data (in an ASCII DataSet, for example), it does not exist. OHLC prices represent ticks on the chart (real trading). Of course in absence of historical options data we're using Synthetic contracts, and we assume (right or wrong) that they closely represent real contract trading.
Consequently, since bid/ask is not available, it's most straightforward to keep it simple and assume that the market price (open of the next bar) is the price you would get. For live trading you could and should use the current live contract. Follow live trades closely for a few days to see what price you could have traded. Using this empirical data, you could calculate and apply a slippage value for backtesting purposes.
So, removing purchasing puts, the strategy becomes -
CODE:
Please log in to see this code.
Size:
Color:
Outstanding! Thank you.
Size:
Color:
I would like to create a way to test an option strategy that I think can build off the work done in this topic. After reviewing this and other WL topics, I have decided backtesting with synthetic options won't work for me because of the unknown variance between historical vs. synthesized pricing data. Instead, I would like to create a "forward-test" (experiment) that uses live data and saves it for ongoing performance analysis, even after a traded option expires
Objective
A walk-forward simulation of a strategy that trades options on signals generated by the underlying. Use real-time (live) option pricing to determine profitability of the trades.
Background and Requirements
Like @tedpenner, I want to buy a call (or put) as minimally in-the-money (ITM) as possible. Since the strikes are $5 apart on the underlying, the strike will be <$5 in the money (ITM). The expiration date on the option will be the first Friday after the current day (1 – 7 days out, depending on the day of the week a position is opened).
The live transaction data must be stored and cumulative (not historical), since historical data won’t be available for options after they expire. Rather, a dataset of simulated trades will be collected over time to gather performance data to compare to a hypothetical performance generated from backtest results on the underlying and assumptions about the option leverage factor. Simulated transaction data would automatically or manually be exported to a spreadsheet or stored in some other fashion.
Challenges
1. I must create an algorithm that constructs the correct symbol based the desired strike price and expiration date. I’m sure the Rounding methods in the code you shared in post #62 will do the trick for the strike. I believe the expiration date can be coded fairly easily. There are some quirks with the option symbol such as weekly options (the ones that expired on Fridays other than the 3rd Friday) having a “W” inserted into the symbol name, but that should be manageable. Also, monthly options actually expire (are priced) at the close of market of the previous day (Thursday). Another detail that will have to be coded.
2. I’m unclear how the simulated pricing will be determined. The underlying has a wide Bid-Ask (B-A) spread, so trading at market would wipe out any profitability. However, the midpoint of the B-A has been a pretty good indicator of market price, based on real-world trading. I see in a trade ticket that WL provides Last, Bid, and Ask prices for a valid option symbol, so I'm hoping I can access this data programmatically. There needs to be a formula based on certain rules to calculate limit pricing on the option.
3. Option trades do not occur on all strikes every minute of the day. My understanding of how WL gets pricing for a trade is from the first real transaction on the next bar. Need to develop a fallback plan for what to do if there is no transaction on the next bar, which happens often).
4. Figuring out how to export simulated trade data to Excel in real time using MS libraries or built-in functions.
Question
The trading strategy (EMA Crossing) in post #62 is sufficient for this experiment. I can make changes to the buy / sell rules in that code. Do you think this code example is a good starting point for developing what I described above?
More fundamentally, I need to know whether it is possible with the WLP platform to do what I have outlined in the Objective section of my post.
Size:
Color:
The code shared in this topic is absolutely outstanding. And artistic. It's a really great example of what can be done with the WLP platform in the right hands (not mine). I managed to back-test 4 days before I got into expired option territory. Of course it should work streaming as well Thank you!
I hacked at the code to make a few significant steps toward my goal. I have a couple of questions:
1. I am using the code from post #21. I didn't use later versions because it sounds like you changed to synthetic options which I am not interested in for this porject. Am I missing anything valuable from later versions of the code?
2. What do you think is the best way to convert (x100) the dollar values to reflect option contracts? Default to buying 100 shares of everything in the PosSizer?
Thanks again for the gift.
Size:
Color: