- ago
I have been using the IB Broker with an IB paper account to evaluate whether I could potentially automate my strategy trading. I would require the following capabilities that I believe represent enhancements to the current version.

General Trading (Stocks, ETF's)
Expose account management functionality to WL8 methods, to provide live broker queries such as account balance, active positions (qty, value), cash available. (These data are currently provided in the Accounts window.)


Options Trading
Provide capability to access or download option tables based on underlying symbol and expiration date. In addition to pricing at different strikes, the Greeks for each unique option should be available as well.
11
1,220
66 Replies

Reply

Bookmark

Sort
- ago
#1
1. It's still a bit unclear why this is needed in your opinion, can you comment Cone's Post #5 here?

https://www.wealth-lab.com/Discussion/Access-Accounts-data-from-broker-programmatically-7914

If it's really necessary we could tag that originating topic as #FeatureRequest.

2. Options data at IB is not possible, this request just duplicates an already rejected feature request. And as you should find out there, Tradier is the answer:

https://www.wealth-lab.com/Discussion/Add-support-for-Options-strategy-design-and-trading-6077

0
Cone8
 ( 28.32% )
- ago
#2
Clarifying... "Options data at IB is not possible"

You cannot request data for expired contracts (at IB or most brokers), but you can get for current and future contracts. We're not supporting the Greeks (yet), but you can get price data right now as described in the Help.
0
- ago
#3
CODE:
1. It's still a bit unclear why this is needed in your opinion

In order to potentially automate the process I go through manually today.

CODE:
, can you comment Cone's Post #5 here?

Cone is correct about TD, but I am talking about Interactive Brokers (IB or IBKR), where this functionality appears to be available through their TWS API.

I want to be clear: I am *not* looking to backtest option strategies on the option symbol or looking for historical option data. That's an entirely different issue and not a requirement for me. I am only looking to have functionality available to support live option trading (assuming trading signals don't require historical option data.)
0
Cone8
 ( 28.32% )
- ago
#4
Again, you can get historic options data for contracts that have not expired. You don't need to use that data for trading. However, to trade options (or any) you need to identify the contract using the specified format in the help.

Here are 2 live orders, entered manually (no data required) -



But if you want the data, just request it in a chart. It must be intraday for IB options -

1
- ago
#5
QUOTE:
2. Options data at IB is not possible,

I think you mean TD
QUOTE:
this request just duplicates an already rejected feature request. :

I respectfully disagree. The feature request you refer to is general, and mine is specific to IB because I've done the research that indicates they support option trading in their API (unlike TD).

Additionally, my feature request does not include for historical option data as the referenced one does. I indicated above. I believe such a request is a standalone request, because of the complexity of specifying the requirements and exclusions of such a feature.

Further, unlike the referenced feature request, mine is not asking to be able to generate signals from option symbols (which relies on historical option data), only the ability to construct symbols and trade them from other signal sources.

QUOTE:
And as you should find out there, Tradier is the answer

I'd have to see what Tradier offers (as an integration to WL8) that IB does not. IB definitely appears to be a more established broker.

However, I'd be interested in looking at Tradier. Is there a Tradier broker extension available I can try?
0
- ago
#6
QUOTE:
Again, you can get historic options data for contracts that have not expired. You don't need to use that data for trading.

I want to make sure we are on the same page. At the risk of repeating myself, I am *not* interested in historical options data.

QUOTE:
However, to trade options (or any) you need to identify the contract using the specified format in the help.

Thank you. Yes, I am well aware.. I have coded this outside WL for quite a while now.
QUOTE:
But if you want the data, just request it in a chart. It must be intraday for IB options -

How do I get the functionality in the title post
QUOTE:
Options Trading
Provide capability to access or download option tables based on underlying symbol and expiration date. In addition to pricing at different strikes, the Greeks for each unique option should be available as well.

from an options chart?
0
Cone8
 ( 28.32% )
- ago
#7
We need a feature request to judge the popularity and to study how best to integrate accessing ad-hoc options data. Instead of a single solution for one broker provider, we'd probably prefer to create an interface to standardize the data access.
0
- ago
#8
QUOTE:
May 3, 2022, 09:07 AM - 2 hours ago
#11
We need a feature request to judge the popularity and to study how best to integrate accessing ad-hoc options data. Instead of a single solution for one broker provider, we'd probably prefer to create an interface to standardize the data access.


I can certainly understand that preference from a strategic pov. I was trying to create a narrowly-focused enhancement that would address a specific use case, which I think covers what most people are looking to do..

If you are wanting to develop something more general, I'm all for it and would be happy to help where I can. However, options trading has much more complexity and there are many different types of options trading besides buying and selling Calls and Puts. Day-trading options is also more demanding than daily trading of options.

There are spreads and other multiple combination option strategies. (I wasn't looking for those.) So, IMO, the first thing would be to define the scope of the enhancement based on anticipated use cases.

BTW, I believe all the elements of this feature request are already supported by the IB API. That's why I led with these. https://interactivebrokers.github.io/tws-api/options.html

I have made a feature request here, as you asked me to. I'll leave it to you to take it from here and let me know if you need additional clarification on the use case I envisioned, or any others I mentioned.
0
Cone8
 ( 28.32% )
- ago
#9
The Account Equity feature works with Position Sizers only. You can't access this value in a script.

This should be broken into 2 separate requests. Why? Because option chains and Greeks are a completely new ball game. We're already getting Account Value, Cash, and Buying Power from brokers, so one request should be limited to accessing those values in a Strategy.

The other should be for option chains and greeks. There are no interfaces made for this and I see it as a non-trivial effort. There at least 3 brokers that could support it.
0
- ago
#10
QUOTE:
This should be broken into 2 separate requests.

I already organized this request (at top of post) into two discrete sections ; General Trading and Options Trading. I can create 2 new FR's, one for each of these. Is that sufficient. Or are you looking for more?

QUOTE:
The other should be for option chains and greeks. There are no interfaces made for this and I see it as a non-trivial effort. There at least 3 brokers that could support it.

I was hoping the BI API would support this using the commands they list in their API. Haven't seen docs on the API's of the other two.

The IB API docs reads like it has a command that will return an Option Chain for a specific underlying symbol and expiration date in tabular form. That should be all that is necessary to construct an option trade, if this table data can be captured in a custom class list or some other C# structure. I believe the returned option chain should be comprehensive, meaning that all the data expected in an option chain (strikes, prices, Greeks) will be in the table.

Unless you already have, if someone familiar with the WL8 IB API implementation can take a look at https://interactivebrokers.github.io/tws-api/options.html, I'm sure you can quickly confirm whether or not the technical implementation would be as straightforward as I am suggesting, at least for IB.
0
Glitch8
 ( 12.10% )
- ago
#11
I think what Cone is getting at is that we don't want to do a bunch of work that's specific to only IB. WL's philosophy is to be open ended. Since many brokers might support options greeks, we would want to build a general interface that ANY broker that wants to can opt in.
0
- ago
#12
Let's rename this topic to serve as the options request. We already have another for the arguable request of programmatic equity value access:

https://www.wealth-lab.com/Discussion/Access-Accounts-data-from-broker-programmatically-7914

I moved related posts to that discussion, making this one focused on options. Multiple unrelated requests should not be packed into one to avoid confusion.
0
- ago
#13
QUOTE:
I think what Cone is getting at is that we don't want to do a bunch of work that's specific to only IB. WL's philosophy is to be open ended.

I completely understand. I suspect that there is tremendous similarity across vendors. in the information the API returns for a specific type of request.

You would know better than I if this has been true for broker API functions WL already supports in some way, such as account balances or open positions. Not in access protocol but in the type of data delivered.

I haven't seen variations across financial vendors in the data option chains contain. If this holds true for the API's, it would be supportive of the "Open-ended" strategy you mention and I hope you find it largely true.
0
Cone8
 ( 28.32% )
- ago
#14
Since this is high on the list and IB is almost there anyway, I'd like to know what the expectations of "download option tables" is with respect to using it in a Strategy.

In my mind, you'd be able to request and obtain the greeks for a specified option contract from a Strategy. I don't see any point of creating a U.I. for an "Option Table" that all the brokers already provide.
0
Glitch8
 ( 12.10% )
- ago
#15
In my mind this will be a new set of virtual methods in BrokerBase and/or DataProviderBase that specific brokers can opt into by implementing those methods.
0
Cone8
 ( 28.32% )
- ago
#16
No problem. I'm just asking about how to consume the "option chain".

Currently, the IBBroker Provider already requests an Option Chain when you call GetOptionsSymbol(), which is already a a virtual method in BrokerBase. The chain is cached to provide the ability to identify a contract symbol that matches the parameters passed to GetOptionsSymbol(). (We need to add some overloads to that method for more specificity.)

Back to my feeble mind, the only additional thing required is a on-demand method that returns the greeks for an option contract returned by GetOptionsSymbol(). Probably this just requires a OptionGreeks type and a method to return it...

public virtual OptionGreeks GetTheGreeks(string OptionSymbol)

IB has some other functions that could be useful in realtime trading -
1. calculateImpliedVolatility() by passing an option and underlying price
2. calculateOptionPrice() using underlying price and IV.
0
- ago
#17
There are a wide variety of constructs for option trades. When I'm opening a position (with any number of constructs such as calls, puts, spreads, etc.), my mental process is:

underlying symbol > exp date > call or put > sell or buy >>
...then manually scan the option table looking for specific parameters within a specific range.

In my case, these Greek parameters include delta falling between two preset values, or the highest or lowest delta not to exceed n, and strike price (these two are correlated through the price of the underlying).

If I understand the proposal above, I will first have to know the unique option symbol before getting its data, like delta or price. In my case I don't know the unique OptionsSymbol until I see where the parameters land in the table. In fact, I don't even know what strikes are available until I see a table for a specific expiration date of the underlying.

Then I place a limit or market order.

Closing a position is a much simpler process since you already know the unique option symbol and just have to decide whether to close at market or limit. This transaction can be completed with a method that depends on the unique option symbol, without delivering a "table.".

My mental construct for opening an option position relies on getting a table of available options that can be scanned for a match with certain parameters. It would not be practical for me to try to "guess" at which options are available by comparing them one by one, because strike prices often change by expiration date for the same underlying. It becomes a "Catch-22".

I suppose there is some other way to do it that I'm not thinking about, but I envision downloading an option table for an underlying within parameter ranges might be best for coding strategies. I know there are other parameters traders use other than delta. The universal solution would be to include all Greeks of all available options that meet all the criteria passed to API.

Naturally the API is constrained by what the broker will provide, and I have little insight into that, except that few brokers that support options trading by API (only IB?).

I hope I understood the question and that this is on point.

Additional note: the broker standard UI is to enter an underlying symbol and select an expiration date. Then the table returned is split into two parts: calls and puts. These are sorted by strike price with Greeks in each column for each strike price.

I apologize if this is too elementary, but it would seem that the solution would require the method to provide only two pieces of information, underlying and expiration date. An additional filtering parameter can limit the number of returned available options (5, 10, 20, All) within a range having strikes n/2 above and n/2 below the underlying's current price.
0
Cone8
 ( 28.32% )
- ago
#18
Proposal or not, you need to identify a contract to request it's data. We do it with the symbol, and you get easily get the symbols with calls to GetOptionsSymbol() passing to it the symbol, strike, right, and days to expiration. If you want to get data for the whole table, then you need to request every symbol in the table.

QUOTE:
I suppose there is some other way to do it
For example, you calculateImpliedVolatility() and then calculateOptionPrice() for various strikes. Or, you look at the bid/ask for each strike required.

Re: the broker standard UI
If you want to manually trade options by clicking in a table, use the broker's app. Our goal is automated trading. If your strategy needs "scan a table", it can certainly do it without the U.I.
0
- ago
#19
In GetOptionsSymbol(), can you please clarify what "symbol" refers to; is it the underlying symbol or the unique symbol in standardized form for options?

QUOTE:
GetOptionsSymbol() passing to it the symbol, strike, right, and days to expiration.


What is "right" above? Typo?
0
Cone8
 ( 28.32% )
- ago
#20
All documented long ago in Help (F1) > Interactive Brokers > Options, and there's even a working code example there - make sure to run it with intraday data.
0
- ago
#21
OK. I see I misinterpreted several key items, and this clarification is helpful.

First, I thought the word "symbol" as a value in the GetOptionsSymbol() method was referring to the option symbol, not the underlying symbol.

Second, I thought this was a start-from scratch effort, not an enhancement to an existing method.

Third, I was not up to speed on the existing method, GetOptionsSymbol().

My suggestions above, therefore, are not relevant. The only thing that comes to mind to respond appropriately to your question is, in addition to making the Greeks accessible, that you also include the option bid/ask (and possibly last) price.
QUOTE:
2. calculateOptionPrice() using underlying price and IV.

Can't the API return current bid/ask/last pricing? Or are you thinking about this as separate function to determine theoretical value (to compare to market price)?
0
Cone8
 ( 28.32% )
- ago
#22
Since options are often illiquid, "Last" is just as often not useful, so Bid or Bid/Ask is the way to go for current pricing.

We still have to study it, but for now I think we need a type that returns the greeks with an option model price another for the bid/ask and last, if it has traded.
0
- ago
#23
QUOTE:
and there's even a working code example there

I'm a bit lost on how to trade the option.
QUOTE:
//execute the strategy rules here, this is executed once for each bar in the backtest history
public override void Execute(BarHistory bars, int idx)
{
if (HasOpenPosition(obars, PositionType.Long))
{
PlaceTrade(obars, TransactionType.Sell, OrderType.Market);
}
else
{
PlaceTrade(obars, TransactionType.Buy, OrderType.Market);
}
}

//Private Variables
BarHistory obars;}
}

Doesn't work. I'm obviously not setting this up properly.
QUOTE:
Execute Exception (TTD,0) Line 39 - Value cannot be null. (Parameter 'key')
Execute Exception (ENPH,0) Line 39 - Value cannot be null. (Parameter 'key')
Execute Exception (SOXL,0) Line 39 - Value cannot be null. (Parameter 'key')
at System.Collections.Generic.Dictionary`2.FindValue(TKey key)
at WealthLab.Core.Synchronizer.GetCurrentIndex(TimeSeriesBase tsb)
at WealthLab.Backtest.UserStrategyExecutor.GetCurrentIndex(BarHistory bh)
at WealthLab.Backtest.Backtester.PlaceTrade(BarHistory bars, TransactionType transType, OrderType orderType, Double price, Int32 positionTag, String signalName)
at WealthLab.Backtest.StrategyBase.PlaceTrade(BarHistory bars, TransactionType transType, OrderType orderType, Double price, Int32 positionTag, String signalName)
at WealthScript1.IBOptionDemo.Execute(BarHistory bars, Int32 idx) in :line 39
at WealthLab.Backtest.UserStrategyExecutor.RegisterParameter(List`1 lst, DateTime dt)

Is there an option trading example for IB?
0
Cone8
 ( 28.32% )
- ago
#24
It certainly can't be done by passing a null bars reference. We're off topic now, but...
Reserving the right to change method calls (because it will change) this currently works for the IB Broker Provider (only) -

Setup:
1. In the IB configuration, select "Midpoint" for Option Chart What to Request
2. INTRADAY only - IB returns option data only for intraday scales.
3. Expired Option data is not available. You can backtest options only with future expirations or with data for past expirations that you've already downloaded.

This strategy buys and sells the next $5 strike with an expiry at least 14 days out when the 10 and 21-period moving average of the underlier crosses over/under. To try it out, I recommend loading the last 4 weeks of data with 30-minute bars. As always, it can take "forever" to download Intraday data from IB, so make sure you give it a good amount of time for the first run with a new symbol.

CODE:
using WealthLab.Backtest; using System; using WealthLab.Core; using WealthLab.Indicators; using System.Collections.Generic; using System.Globalization; using WealthLab.InteractiveBrokers; // *** This won't be required later namespace WealthScript81 {    public class IntradayOptionDemo : UserStrategyBase    {       public IntradayOptionDemo()       {          AddParameter("Strike Increment", ParameterType.Int32, 5, 1, 10, 1);          AddParameter("Contracts", ParameterType.Int32, 1, 1, 10, 1);       }       //create indicators and other objects here, this is executed prior to the main trading loop       public override void Initialize(BarHistory bars)       {          _sma = SMA.Series(bars.Close, 10);          _sma2 = SMA.Series(bars.Close, 21);          StartIndex = 21;          PlotIndicatorLine(_sma, WLColor.Green);          PlotIndicatorLine(_sma2, WLColor.Red);          _increment = Parameters[0].AsInt;          _contractQty = Parameters[1].AsInt;       }       public override void Execute(BarHistory bars, int idx)       {          Position pos = FindOpenPositionAllSymbols(123);          if (pos == null)          {             if (_sma.CrossesOver(_sma2, idx)) // || idx == bars.Count - 1)             {                // select the next highest $5 strike                double strike = Math.Ceiling(bars.Close[idx] / _increment) * _increment;                string contractSymbol = IBHistorical.Instance.GetOptionsSymbol(bars, OptionType.Call, strike, bars.DateTimes[idx], 14);                if (_obh.ContainsKey(contractSymbol))                   _obars = _obh[contractSymbol];                else                {                   _obars = GetHistory(bars, contractSymbol);                   _obh[contractSymbol] = _obars;                }                if (_obars == null)                {                   WriteToDebugLog(contractSymbol + " was null on " + bars.DateTimes[idx].ToShortDateTimeString());                   return;                }                Transaction tn = PlaceTrade(_obars, TransactionType.Buy, OrderType.Market, 0, 123);                tn.Quantity = _contractQty;             }          }          else          {             if (_sma.CrossesUnder(_sma2, idx))             {                               ClosePosition(pos, OrderType.Market);             }          }       }       public override void BacktestComplete()       {          foreach (string symbol in _obh.Keys)             WriteToDebugLog(symbol + "\t" + _obh[symbol].SecurityType);          // Indicate the trades          foreach (Position p in GetPositionsAllSymbols())          {             PlotBarHistory(p.Bars, p.Symbol);             if (!p.NSF)             {                DrawTextVAlign(_triangleUp, p.EntryBar, p.Bars.Low[p.EntryBar] * 0.95, VerticalAlignment.Top, WLColor.Black, 16, 0, 0, p.Symbol, true);                DrawTextVAlign(_triangleDn, p.ExitBar, p.Bars.High[p.ExitBar] * 1.05, VerticalAlignment.Bottom, WLColor.Black, 16, 0, 0, p.Symbol, true);             }          }       }       //declare private variables below       int _contractQty = 1;       SMA _sma;       SMA _sma2;       int _increment;       Dictionary<string, BarHistory> _obh = new Dictionary<string, BarHistory>();       BarHistory _obars;       BrokerBase _broker;       string _triangleUp = "â–²";       string _triangleDn = "â–¼";    } }


Result -



0
- ago
#25
@Cone Thanks for the instructions and the sample code.

I'm able to run this with a few symbols but for some reason, AMZN causes a "Index was out of range error." Any idea why?
0
Cone8
 ( 28.32% )
- ago
#26
No, you'd have to give me the details of your interval and Data Range.

I just noticed that I inadvertently left the " || idx = bars.Count - 1" condition in the code above to always generate a Signal. I've just commented that out.
0
- ago
#27
30 minutes / 4 weeks
0
- ago
#28
The problem with symbol AMZN went away. I don't think it had anything to do with the symbol. I suspect other symbols would have failed at that time as well, but AMZN was the one I was trying at the time (after other symbols were tested and worked). I think a WL restart fixed it. Deficient troubleshooting on my part. Sorry for the distraction.
1
- ago
#29
QUOTE:
Since options are often illiquid, "Last" is just as often not useful, so Bid or Bid/Ask is the way to go for current pricing

This is my experience as well. The only time I find Last to be somewhat useful is as a starting point for placing a Limit trade when the Bid/Ask spread is unusually large and the Last is reasonably current and falls within the Bid/Ask
0
- ago
#30
@Cone I have been successfully experimenting with the option trading code you provided and want to start coding a strategy that yields daily signals on an underlying and trades its appropriate option the day after the signal. I am trying to figure out the best way to do this since I can't get bar history (from IB) for the option symbol using a daily scale.

Should I look at the HistoryScales() method or the GetHistoryUnsynched() method or tackle this some other way? Seems that something like SetScaleDaily() from WL5 might be what I'm looking for. Is there a WL8 equivalent?
0
Cone8
 ( 28.32% )
- ago
#31
See this in the QuickRef -
BarHistoryCompressor.ToDaily()
TimeSeriesSynchronizer.Synchronize()
0
- ago
#32
@Cone thank you for guiding me to these functions. Together with the code you sent in Past #24 (and other support), I have been able to get a skeletal option trading strategy working with IB. One note, I had to make a change to your code to prevent RT error for positions that are still Open.

Old Code
CODE:
if (!p.NSF) { DrawTextVAlign(_triangleUp, p.EntryBar, p.Bars.Low[p.EntryBar] * 0.95, VerticalAlignment.Top, WLColor.Black, 16, 0, 0, p.Symbol, true); DrawTextVAlign(_triangleDn, p.ExitBar, p.Bars.High[p.ExitBar] * 1.05, VerticalAlignment.Bottom, WLColor.Black, 16, 0, 0, p.Symbol, true); }

New Code
CODE:
            if (!p.NSF)             {                DrawTextVAlign(_triangleUp, p.EntryBar, p.Bars.Low[p.EntryBar] * 0.95, VerticalAlignment.Top, WLColor.Black, 16, 0, 0, p.Symbol, true);                //prevent RT error if position still open                if (p.ExitBar != -1)                   DrawTextVAlign(_triangleDn, p.ExitBar, p.Bars.High[p.ExitBar] * 1.05, VerticalAlignment.Bottom, WLColor.Black, 16, 0, 0, p.Symbol, true);             }

A few observations:
1. If the backtest period is too long, the option the program would have selected may no longer be available. This can be confusing at first as a more current option will be selected instead of the actual one in the past. As a result, I am l limiting my timeframe to 2 months, where I don't run into this problem (options disappearing from the table). In my case I am not concerned with backtest data on options, only generating live signals to auto-trade.
2. In the current code implementation, all the cool charting you coded will only appear on a single symbol chart in a portfolio backtest, apparently the last one that was randomly processed. This requires entering each of the symbols from the portfolio until you find the one that is currently displaying these charts.
3. For live trading, I realized I have to add some code to Close an option position before it expires, as I personally don't want it to trigger a trade for the underlying if it is in the money at expiration. I am thinking I can cull the expiration date from the option symbol and include some OR logic in the Sell section to handle this.
4. It's not uncommon for options to have strike prices at 0.50 increments. I tested this by changing the strike increment parameter / variable to a double and used the value of 0.5 for the increment. The strategy returned:

TSLA230317C196.67

So that appears to cover the waterfront!
0
Cone8
 ( 28.32% )
- ago
#33
We can talk about options if you open another conversation. We're off topic here.
0
- ago
#34
It's too late Robert. It seems to me there's almost nothing in this thread that has to do with "Access to live account info" - it's all about options 😂

I've done what Post #12 above suggested: renamed the topic and split it into two requests, this and... https://www.wealth-lab.com/Discussion/Access-to-live-account-information-7915
0
- ago
#35
Hi @Eugene. Thanks. I kind of noticed that myself earlier today. Not sure how we got there.
0
- ago
#36
@Cone wrote:
QUOTE:
Since this is high on the list and IB is almost there anyway, I'd like to know what the expectations of "download option tables" is with respect to using it in a Strategy.


Hi again @Eugene. I do recall this was near the top of the Feature Request list. Now it's on the bottom. When you renamed this topic, did it lose its votes? Can that be corrected?
0
- ago
#37
No votes have been lost. The original topic "Access to live account information" has kept its name and 10 votes which it had prior to my extraction. I remember that subject was referred to in other forum discussions and voted for. Users typically find topic titles to vote for on the Wishlist page, and "options trading" had never been part of that discussion's title before the extraction.
0
Cone8
 ( 28.32% )
- ago
#38
Something changed Eugene. The topic has something to do with supporting Option Chains and Trading. It was one of the top 5.
0
- ago
#39
I doubt it could've been on top 5 with its 10 votes but it's ranked #9 now:
https://www.wealth-lab.com/Discussion/Access-to-live-account-information-7915
https://www.wealth-lab.com/wishlist
0
Cone8
 ( 28.32% )
- ago
#40
Live Accounts is considered "complete". There is a solution for that.

Option Chain and Greeks has been deleted. It no longer appears in the wish list. That one had at least 11 votes.
0
Cone8
 ( 28.32% )
- ago
#41
Reviewing it, this is the topic, but it was renamed and lost all the votes.
0
- ago
#42
I haven't deleted anything nor modified the voting. The 10 votes went there because "Access to live account info" was the name and at the risk of repeating, that's how the topic was voted for from the wishlist =>
https://www.wealth-lab.com/Discussion/Access-to-live-account-information-7915

Are you trying to convince me that the voters would find "Access to live account info", read two dozen posts of an offtopic conversation regarding options, and vote for that?
0
Cone8
 ( 28.32% )
- ago
#43
Sorry, but the main topic title with the votes had these 3 words in it:
Option, Chain, Greeks
0
Glitch8
 ( 12.10% )
- ago
#44
We recently experienced an event on the web site that forced me to rename a number of topics manually. It’s probable that I misnamed a topic.
0
Cone8
 ( 28.32% )
- ago
#45
Yup, forgot about that. Nonetheless, here's the proof - they only had 1 capture of it from 9/25/2022 - but even here it had 8 votes:

https://web.archive.org/web/20220925042256/https://www.wealth-lab.com/wishlist/
0
- ago
#46
That's a game changer. Let me transfer those votes here and rename the topic then.

EDIT: Done.
1
- ago
#47
Hi guys. A month ago, this FR was near the top of the list. Now there are a number of new FR's that were upvoted, so this has gone down significantly.

I would like to begin a serious effort to write a strategy to fully automate my semi-manual options trading process, currently with Fidelity, and move it to IB. I've done a bit of sample testing to familiarize with current functionality but have been holding back on diving into production coding waiting to see if new functionality listed here might be nearing release. Does it look like it's on the horizon or do you suggest I proceed with what's currently available in WL8 to auto-trade options?
0
Cone8
 ( 28.32% )
- ago
#48
There's no barrier or need for anything from us to create option trading strategies in WealthLab with the IB Provider. It's covered in the User Guide > Extensions > Interactive Brokers with examples. What's missing?
0
- ago
#49
Mainly that my strategy of option strike selection is based on the Delta of an available strike falling within a Delta range and calculated max price, for a given expiration date. I won't have access to the Delta for a given strike contract, to know if I want to go higher or lower strike. The best I can do is with the current functionality is to use % from the current underlying price as a proxy for Delta.

I did a quick analysis of correlation between Delta and strike price % < underlying (since I buy an in-the-money strike) based on my historical trades and was surprised at the wide variation.

Correction: Table reformatted for clarity

CODE:
Long Call Strike % below UL Std Dev Option Strategy 1 -11% 6% Option Strategy 2 -8% 41%
0
Cone8
 ( 28.32% )
- ago
#50
In the next IB Provider update, I'll rig up the Greeks with the understanding that the calls could change (break) with a future implementation.
0
- ago
#51
Cone & all - thank you for all your sharings on the options topic. I am interested in developing a basic option strategy, which I see appears to be of interest to others as well. From another topic I learned Tradier is WL's preferred broker for options. Are you able to show a #24 version for Tradier - I seem unable to make the code changes to work with Tradier. Thank you !
0
- ago
#52
Thanks! Look forward to coding with it.
0
Cone8
 ( 28.32% )
- ago
#53
I activated the feature request and am working on it. Will be in Build 36.
0
- ago
#54
Wow. Terrific.
0
- ago
#55
I have started to test the new functionality for options trading, starting with the modified method, GetOptionsSymbol(). I have the following questions:

1. I have been unable to find more details or examples using this method in the QuickRef. Is there another source or is it just too early for docs? I did watch the build release video. I think I understand all of the variables in the method except for closetStrike. What does this bool variable do? It appears to (sometimes) change the option selected by a single strike. As the debug text below shows, when set to TRUE, the option selected for SPY and QQQ is one strike higher than when set to FALSE. The selected strike for IWM and EEM is not affected by this variable. There is no nnn.50 strike price for any of these underlyings. Only IWM had a strike price that was an integer number.

closestStrike = true
CODE:
               string contractSymbol = IBHistorical.Instance.GetOptionsSymbol(bars, OptionType.Call, strike, expiration, minDaysToExpire, false, false, true);

QUOTE:
Debug
---Symbol by Symbol Debug Logs---
---EEM---
Strike = 38.5
EEM230818C38.5 was null on 5/31/2023 16:00
Strike = 38.5
EEM230818C38.5 was null on 6/1/2023 10:00
Strike = 38.5
EEM230818C38.5 was null on 6/1/2023 10:30
Strike = 39
# of Contracts to buy is 18
6/1/2023 Contract Price is 110.00
6/8/2023 Time to Close Position
Strike = 40
# of Contracts to buy is 19
6/9/2023 Contract Price is 104.00
---QQQ---
Strike = 351.5
# of Contracts to buy is 1
5/30/2023 Contract Price is 1,552.00
---IWM---
Strike = 176
# of Contracts to buy is 2
6/1/2023 Contract Price is 692.00
---SPY---
Strike = 421.5
# of Contracts to buy is 1
5/30/2023 Contract Price is 1,398.00
SPY230818C421 Option

closestStrike = false
CODE:
               string contractSymbol = IBHistorical.Instance.GetOptionsSymbol(bars, OptionType.Call, strike, expiration, minDaysToExpire, false, false, false);

QUOTE:
Debug
---Symbol by Symbol Debug Logs---
---EEM---
Strike = 38.5
EEM230818C38.5 was null on 5/31/2023 16:00
Strike = 38.5
EEM230818C38.5 was null on 6/1/2023 10:00
Strike = 38.5
EEM230818C38.5 was null on 6/1/2023 10:30
Strike = 39
# of Contracts to buy is 18
6/1/2023 Contract Price is 110.00
6/8/2023 Time to Close Position
Strike = 40
# of Contracts to buy is 19
6/9/2023 Contract Price is 104.00
---QQQ---
Strike = 351.5
# of Contracts to buy is 1
5/30/2023 Contract Price is 1,488.00
---IWM---
Strike = 176
# of Contracts to buy is 2
6/1/2023 Contract Price is 692.00
---SPY---
Strike = 421.5
# of Contracts to buy is 1
5/30/2023 Contract Price is 1,314.00
SPY230818C422 Option


2. The calculation for the strike price may result in a value of nnn.50 as shown in the debug outputs above. It appears that EEM generates a null symbol because strike of nnn.50 is not available. But it does not do so for SPY or QQQ. Why doesn't EEM just select the next higher or lower strike?

3. One challenge I'm having is needing to "guess" at what the actual strike increments will be for a given underlying. This can depend on price, expiration date, open interest and probably other variables. I assumed a potential increment of $0.50 in the strike estimation calculation because this is a strike (nnn.50) for lower value underlyings. In other words I don't know if the available options have a $0.5, $1, or $5, etc. increment without looking at an option chain. I have to just test for it. I'm not sure if this is a viable approach, but I may have a better feel when I get clarification on my questions 1 & 2 above. From a coding structure perspective, I envision looping to get the option I "want" by searching through available strikes.

Backtest
(For some reason the Image attach function is not working for me.)
0
- ago
#56
Backtest
0
Cone8
 ( 28.32% )
- ago
#57
I'm working on a blog article with more info and examples, so I'll leave it at that for now. The examples in the help should be enough to get you going.

We're going to release another WL build with the Y! streaming fix, and, the IB Provider will get an upgrade too....

IB's Option Chain doesn't specify which strikes are valid at each expiration - you just get all the strikes and dates to work with. Right now, you're on your own to find valid strikes by adjusting the price to GetOptionsSymbol(). IB Build 29 will have logic to check if the first strike found has traded, and if it hasn't, will adjust up (call) or down (put) to the nearest $5 strike, which is almost always valid.
0
- ago
#58
How do I locate the examples in Help?
0
Cone8
 ( 28.32% )
- ago
#59
You use Interactive Brokers, right?
Look for that.
0
- ago
#60
found it. thanks.
0
- ago
#61
@Cone FYI it appears that with
CODE:
         string contractSymbol = "QQQ230721C355";          OptionGreek greek = IBHistorical.Instance.GetGreeks(contractSymbol);

greek.OptionPrice is yielding the BId price, not the midpoint, at least for this contract during live hours.

A related question is whether Bid and Ask can be accessed.

If you prefer to defer a response until you do your doc update, I can wait. Just want to make sure I'm documenting what I think I'm seeing.
0
Cone8
 ( 28.32% )
- ago
#62
One price is returned with in the TWS API tickOptionComputation callback. Here's IB's documentation for that price:

optPrice the option price
0
- ago
#63
very detailed description lol
0
- ago
#64
@Cone can you explain how the following code works from the sample code you provided above (entry #24).

CODE:
if (_obh.ContainsKey(contractSymbol)) _obh[contractSymbol] = _obars; else { _obars = GetHistory(bars, contractSymbol); _obh[contractSymbol] = _obars; } if (_obars == null) { WriteToDebugLog(contractSymbol + " was null on " + bars.DateTimes[idx].ToShortDateTimeString()); return; }

I am guessing you set up a dictionary of option symbols and bars for that symbol (_obars) to avoid downloading bar history if unnecessary? I see that if the key (option symbol) is not found in the dictionary, the code fetches _obars using GetHistory() and then inserts the bars object into the dictionary paired with the symbol key.

But if it finds the key it seems to do the same thing, which I thought would make an IF statement moot. Is this part of the code to update _obars or not create duplicate keys? In that case where was _obars instantiated or how did it get updated?
0
Cone8
 ( 28.32% )
- ago
#65
The idea is to hit GetHistory for a contract only once. If the logic trades/switches between many strkes, you don't want to wait for a GetHistory call each time. For IB, these take a LONG time. Still it will take a long time for the first download even hitting each contract just once. If you're trading live and don't need the actual option data, it would be better to load a synthetic contract to avoid the delays.

QUOTE:
I am guessing you set up a dictionary of option symbols and bars for that symbol (_obars) to avoid downloading bar history

No need to guess. The Dictionary is _obh, just look for the Dictionary declaration.

QUOTE:
But if it finds the key it seems to do the same thing
Good catch. Copy and paste error. Corrected in Post #24!

By the way, the signature changed for GetOptionsSymbol.

CODE:
//WAS: string contractSymbol = IBBroker.Instance.GetOptionsSymbol(bars.Symbol, OptionType.Call, strike, bars.DateTimes[idx], 14); //IS: string contractSymbol = IBHistorical.Instance.GetOptionsSymbol(bars, OptionType.Call, strike, bars.DateTimes[idx], 14);
0
- ago
#66
QUOTE:
No need to guess.

I meant I was guessing the reason for this code is to avoid unnecessary downloads, which you confirmed. Very cool idea!
QUOTE:
Good catch. Copy and paste error.

That fixed a problem I was chasing unsuccessfully: the strategy taking an hour or more to complete during non-trading hours. Now it takes a few seconds. Thanks.
QUOTE:
By the way, the signature changed for GetOptionsSymbol.

Yes, I'm aware but thanks for the reminder. I'm using the updated syntax and it's working fine.
1

Reply

Bookmark

Sort