Add ability to stream market data

This commit is contained in:
moshferatu 2023-11-06 11:55:16 -08:00
parent 396ca35021
commit 24a1e89664
2 changed files with 25 additions and 1 deletions

View File

@ -0,0 +1,16 @@
from datetime import datetime
from ib_insync import Option
from ibkr.client import Client
from ibkr.exchange import SMART
client = Client(host = '127.0.0.1', port = 7497)
expiration = datetime.now().strftime('%Y%m%d')
contract = Option('SPX', expiration, 4350.0, 'P', exchange = SMART, currency = 'USD')
contract.tradingClass = 'SPXW'
market_data = client.get_market_data(contract, streaming = True)
while True:
print('Bid:', market_data.bid)
print('Ask:', market_data.ask)
client.ib.sleep(secs = 2.0)

View File

@ -2,7 +2,7 @@ import pandas as pd
from datetime import datetime
from .exchange import SMART
from ib_insync import IB, Index, Option
from ib_insync import Contract, IB, Index, Option
from ib_insync.util import isNan
from .market_data_type import LIVE
from typing import Callable
@ -19,6 +19,14 @@ class Client:
self.ib.qualifyContracts(underlying)
return self.ib.reqTickers(underlying)[0]
def get_market_data(self, contract: Contract, streaming: bool = False):
market_data = self.ib.reqMktData(contract, '',
snapshot = not streaming, regulatorySnapshot = False)
while isNan(market_data.bid) or isNan(market_data.ask):
# TODO: Add a timeout.
self.ib.sleep()
return market_data
def get_option_chain(self, symbol: str, expiration: datetime, sub_symbol: str = None,
contract_filter: Callable = None) -> pd.DataFrame:
expiration_date = expiration.strftime('%Y%m%d')