Lean icon indicating copy to clipboard operation
Lean copied to clipboard

[Live] - Holdings avg. price vs. current price can be mismatched depending on data feed

Open gsalaz98 opened this issue 5 years ago • 8 comments

Expected Behavior

The holdings acquired price remains at the same scale as the current price

Actual Behavior

Sometimes, when switching between Interactive Brokers and QC data feed (using IB as the brokerage), the scales changes for holdings vs. current price:

image

^^^ Might only apply to ZC futures

image

Another related finding. This Futures Options' contract's holdings value is off the charts, but might be real because of contract multiplier -- might be a different issue altogether.

Potential Solution

N/A

Reproducing the Problem

Unsure if this will 100% replicate, but place an order in the QC data feed (using IB as brokerage) for ZC contracts. Then, switch to IB data feed and compare the prices the contracts were bought at vs. current holdings

System Information

N/A, cloud

Checklist

  • [x] I have completely filled out this template
  • [x] I have confirmed that this issue exists on the current master branch
  • [x] I have confirmed that this is not a duplicate issue by searching issues
  • [x] I have provided detailed steps to reproduce the issue

gsalaz98 avatar Jan 29 '21 23:01 gsalaz98

I think this might relate to the ContractDetails.PriceMagnifier field in IB - for ZC and several other futures this is set to 100 as the prices are quoted in cents rather than dollars on the exchange.

From what I can see InteractiveBrokersBrokerage passes through prices for ticks and order fills in cents, and expects to receive limit orders etc with the cent price. (Current holdings are given a dollar price at startup though.)

So, a potential fix would be to fetch the ContractDetails for each symbol subscribed to (at least for futures, don't know if this field is used for other contracts), and adjust prices coming in and out, consistent with the fix for #5297.

Not sure what your plans are for this, but happy to help if I can?

spdjudd avatar Sep 10 '21 08:09 spdjudd

Hey @spdjudd!

happy to help if I can

Sounds great, ty! I think the first step here is to have some repeatable steps for the reproduction of the issue to determine and assert what are the parts affected too, which will determine the scope of the fix (adjust holdings/orders/etc) 👍 do you mind going through this?

So, a potential fix would be to fetch the ContractDetails for each symbol subscribed to (at least for futures, don't know if this field is used for other contracts), and adjust prices coming in and out, consistent with the fix for #5297.

yes, believe the brokerage already has a cache of _contractDetails and a method to request it if not present

Martin-Molinero avatar Sep 10 '21 15:09 Martin-Molinero

Sure, I'll go through it next week and provide steps

spdjudd avatar Sep 10 '21 15:09 spdjudd

To start with I've created a version of BasicTemplateFuturesAlgorithm that subscribes to ZC, and alternates submitting market orders to go long one contract then liquidate. I've also run a couple of tests where I restart while the strat is long, so it picks up existing holdings at startup. This is all using IB as both brokerage and data feed.

For context ZC is quoted in cents (https://www.cmegroup.com/markets/agriculture/grains/corn.contractSpecs.html), currently the March 22 contract is trading around 524c / $5.24

Here's a selection of log output:

Start Lean while the account is long 1 contract ZC - price is correctly picked up in dollars: 20210914 15:15:29.892 TRACE:: BrokerageSetupHandler.Setup(): Has existing holding: ZC14H22: 1 @ $5.240564 - Market: $5.2357502 - Conversion:

20210914 15:15:40.717 TRACE:: Context: <OnWarmupFinished>, holding: ZC XWSF913V2I3P, Quantity: 1, HoldingsCost: 26202.82000000, AveragePrice: 5.240564, CurrentPrice: 5.2357502

Receive a data slice - TradeBar close price is in cents: 20210914 15:16:00.022 TRACE:: OnData: ZC14H22: ClosePrice: 524

Submit a market order for 1 contract - fill price is returned in cents: 20210914 15:16:07.985 TRACE:: InteractiveBrokersBrokerage.HandleOrderStatusUpdates(): OrderId: 1893, Status: Filled, Filled: 1, Remaining: 0, AverageFillPrice: 523.75, PermId: 1438694537, ParentId: 0, LastFillPrice: 523.75, ClientId: 0, WhyHeld: ,MktCapPrice: 0

New holding resulting from this order uses the cent price and calculates the wrong HoldingsCost ($2.62M vs $26.2k): 20210914 15:16:08.000 TRACE:: Context: <OnOrderEvent>, holding: ZC XWSF913V2I3P, Quantity: 1, HoldingsCost: 2618750.0000, AveragePrice: 523.75, CurrentPrice: 524.125

Submit a LimitOrder to buy 1 contract with limit $5.50 - should fill immediately given market is at $5.24 but doesn't fill: 20210914 15:58:00.873 TRACE:: Debug: New Order Event: Time: 09/14/2021 15:58:00 OrderID: 1 EventID: 1 Symbol: ZC14H22 Status: Submitted Quantity: 1 LimitPrice: 5.5 Message: Interactive Brokers Order Event

So when InteractiveBrokersBrokerage downloads the current holdings at startup the price is given correctly in USD, giving a correct holdings cost of $26.2k. All other interactions - Trade/QuoteBars, OrderEvents etc pass through the cent price as USD, meaning HoldingsCost for a position that was opened in the current session is 100x too big (shown as $2.62M above). Limit orders are clearly assuming the provided limit price is in cents.

The code's not that interesting but attached here - let me know if there are any other useful steps/outputs I can provide: BasicTemplateFuturesAlgorithm.txt

Happy to work on a PR or help test etc.

spdjudd avatar Sep 14 '21 16:09 spdjudd

Awesome @spdjudd 💯

So when InteractiveBrokersBrokerage downloads the current holdings at startup the price is given correctly in USD, giving a correct holdings cost of $26.2k. All other interactions - Trade/QuoteBars, OrderEvents etc pass through the cent price as USD, meaning HoldingsCost for a position that was opened in the current session is 100x too big (shown as $2.62M above). Limit orders are clearly assuming the provided limit price is in cents.

Sounds good 👍. Posting a potential solution bellow to be called on each use case normalizing into Lean (dollars) or IB (cents) expected prices

/// <summary>
/// Helper method to normalize a provided price to the Lean expected unit
/// </summary>
private decimal NormalizePriceToLean(decimal price, Contract contract, Symbol symbol)
{
    // which other security type should be normalized: FOPs?
    if (symbol.SecurityType == SecurityType.Future)
    {
        return price / GetContractPriceMagnifier(contract, symbol);
    }
    return price;
}

/// <summary>
/// Helper method to normalize a provided price to the brokerage expected unit, for example cents
/// </summary>
private decimal NormalizePriceToBrokerage(decimal price, Contract contract, Symbol symbol)
{
    // which other security type should be normalized: FOPs?
    if (symbol.SecurityType == SecurityType.Future)
    {
        return price * GetContractPriceMagnifier(contract, symbol);
    }
    return price;
}

/// <summary>
/// Will return the price magnifier for the requested symbol
/// </summary>
private decimal GetContractPriceMagnifier(Contract contract, Symbol symbol)
{
    var uniqueKey = GetUniqueKey(contract);
    if (!_contractDetails.TryGetValue(uniqueKey, out var contractDetails))
    {
        contractDetails = GetContractDetails(contract, symbol);
        if (contractDetails == null)
        {
            Log.Error("");
            return 1;
        }
    }
    return contractDetails.PriceMagnifier;
}

Martin-Molinero avatar Sep 14 '21 20:09 Martin-Molinero

Looks good!

There are a couple of other changes required to have the contract and symbol available at the point each conversion needs to happen, specifically in HandleCommissionReport()/HandleExecutionDetails() for generating order fills, ConvertTradeBar() in the history query and HandleTickPrice().

I've tested the version attached here and it successfully addresses all the issues from my previous test: InteractiveBrokersBrokerage.cs.txt

Haven't been able to test the history query as I don't have a working market data subscription for IB right now (only delayed data)

spdjudd avatar Sep 15 '21 15:09 spdjudd

Hey @spdjudd!

I've tested the version attached here and it successfully addresses all the issues from my previous test:

Nice! do you mind going ahead opening the PR with the current changes 👌 + any // TODO comments so we can tackle/review it from there?

Martin-Molinero avatar Sep 15 '21 23:09 Martin-Molinero

Sure - I've opened #5930 but will need a bit more time to sort out testing. I've run tests using algos as described above, and existing unit tests pass, except for the History request ones that I can't run because I don't have IB market data. There are also a couple of tests that restart the IB connection that are failing, but that seems to be because of a difference with the newest IB Gateway rather than my changes.

spdjudd avatar Sep 16 '21 17:09 spdjudd