def get_valid_spy_contract(idx) -> OptionContract: from ib_insync import IB, Stock ib = IB() ib.connect(clientId=idx + 1) ib_stk_con = Stock(symbol="SPY", exchange="SMART", currency="USD") ib_details = ib.reqContractDetails(ib_stk_con)[0] ib.reqMarketDataType(4) tick = ib.reqMktData(contract=ib_stk_con, snapshot=True) while np.isnan(tick.ask): ib.sleep() ask = tick.ask ib_con_id = ib_details.contract.conId ib_chains = ib.reqSecDefOptParams( underlyingSymbol="SPY", futFopExchange="", underlyingSecType="STK", underlyingConId=ib_con_id, ) ib_chain = ib_chains[0] ib_chain.strikes.sort(key=lambda s: abs(s - ask)) strike = ib_chain.strikes[0] expiration_str = ib_chain.expirations[idx] expiration_date = datetime.strptime(expiration_str, "%Y%m%d") spy_contract = OptionContract( symbol="SPY", strike=strike, right=Right.CALL, multiplier=int(ib_chain.multiplier), last_trade_date=expiration_date, ) ib.disconnect() return spy_contract
def main(ib: IB): try: logger.getLogger().info("Connecting...") ib.connect(config.HOST, config.PORT, clientId=config.CLIENTID, timeout=0) ib.reqMarketDataType(config.DATATYPE.value) except NameError: # got this block from https://groups.io/g/insync/message/4045 #self.num_disconnects += 1 print(datetime.datetime.now(), 'Connection error exception', self.num_disconnects) #self.ib.cancelHistoricalData(bars) log.info('Sleeping for 10000 sec...') ib.disconnect self.ib.sleep(10000) ib.connect(config.HOST, config.PORT, clientId=config.CLIENTID, timeout=0) # except OSError: # log.info("main try except OS errror > Connection Failed.") # sys_exit() app = App(ib) app.run()
def main(ib: IB): logger.getLogger().info("Connecting...") ib.disconnect() ib.waitOnUpdate(timeout=0.5) #added to handle is client already in use https://github.com/erdewit/ib_insync/issues/76 randomClientID = random.randint(1,250) log.info("random client ID: {CI}".format(CI=randomClientID)) ib.connect(config.HOST, config.PORT, clientId=randomClientID,timeout=0) #ib.connect(config.HOST, config.PORT, clientId=config.CLIENTID,timeout=0) ib.reqMarketDataType(config.DATATYPE.value) # try: # logger.getLogger().info("Connecting...") # ib.connect(config.HOST, config.PORT, clientId=config.CLIENTID,timeout=0) # #ib.connect(config.HOST, config.PORT, clientId=config.CLIENTID,timeout=0) # ib.reqMarketDataType(config.DATATYPE.value) # except NameError: # got this block from https://groups.io/g/insync/message/4045 # #self.num_disconnects += 1 # print(datetime.datetime.now(), 'Connection error exception', self.num_disconnects) # #self.ib.cancelHistoricalData(bars) # log.info('Sleeping for 10sec...') # ib.disconnect # self.ib.sleep(10) # ib.connect(config.HOST, config.PORT, clientId=config.CLIENTID,timeout=0) # except OSError: # log.info("main try except OS errror > Connection Failed.") # sys_exit() app = App(ib) app.run()
def main(ib: IB): try: logger.getLogger().info("Connecting...") ib.connect(config.HOST, config.PORT, clientId=config.CLIENTID) ib.reqMarketDataType(config.DATATYPE.value) except OSError: logger.getLogger().error("Connection Failed.") sys_exit() app = App(ib) app.run()
class Window(qt.QWidget): def __init__(self, host, port, clientId): qt.QWidget.__init__(self) self.edit = qt.QLineEdit('', self) self.edit.editingFinished.connect(self.add) self.table = TickerTable() self.connectButton = qt.QPushButton('Connect') self.connectButton.clicked.connect(self.onConnectButtonClicked) layout = qt.QVBoxLayout(self) layout.addWidget(self.edit) layout.addWidget(self.table) layout.addWidget(self.connectButton) self.connectInfo = (host, port, clientId) self.ib = IB() self.ib.pendingTickersEvent += self.table.onPendingTickers def add(self, text=''): text = text or self.edit.text() if text: contract = eval(text) if (contract and self.ib.qualifyContracts(contract) and contract not in self.table): ticker = self.ib.reqMktData(contract, '', False, False, None) self.table.addTicker(ticker) self.edit.setText(text) def onConnectButtonClicked(self, _): if self.ib.isConnected(): self.ib.disconnect() self.table.clearTickers() self.connectButton.setText('Connect') else: self.ib.connect(*self.connectInfo) self.ib.reqMarketDataType(2) self.connectButton.setText('Disonnect') for symbol in ('EURUSD', 'USDJPY', 'EURGBP', 'USDCAD', 'EURCHF', 'AUDUSD', 'NZDUSD'): self.add(f"Forex('{symbol}')") self.add("Stock('TSLA', 'SMART', 'USD')") def closeEvent(self, ev): asyncio.get_event_loop().stop()
logger.debug("Hit take profit") logger.debug(f"{self.take_profit}") logger.debug( "----------------------------------------------") self.cancel_order(self.stop_loss.order) if __name__ == "__main__": import logging import sys logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler(sys.stdout)) logger.addHandler(logging.FileHandler("trades.log")) ib = IB() ib.connect("127.0.0.1", 4002, clientId=1) # TWS=7496, PAPER=7497, GTW=4001 ib.reqMarketDataType(1) # this isn't a proper way to roll the f*****g futures ES = ib.reqContractDetails(Future(symbol="ES", exchange="GLOBEX"))[0].contract MES = ib.reqContractDetails(Future(symbol="MES", exchange="GLOBEX"))[0].contract ds = DocStrat(ib=ib, es=ES, mes=MES) logger.debug("Doc Strategy instantiated") ds.run()
def get_option_chain( ib: IB, qualified_contract: Contract, expirations: str, use_delayed_data=False, strike_min=None, strike_max=None, strike_modulus=None, rights=["P", "C"], ) -> pd.DataFrame: """ TODO: Write documentation """ if use_delayed_data: ib.reqMarketDataType(3) [ticker] = ib.reqTickers(qualified_contract) current_price = ticker.marketPrice() strike_min = strike_min or current_price * 0.90 strike_max = strike_max or current_price * 1.10 chains = ib.reqSecDefOptParams(qualified_contract.symbol, '', qualified_contract.secType, qualified_contract.conId) chain = next(c for c in chains if c.tradingClass == qualified_contract.symbol and c.exchange == qualified_contract.exchange) if strike_modulus: strikes = [ strike for strike in chain.strikes if strike_min < strike < strike_max and strike % strike_modulus == 0 ] else: strikes = [ strike for strike in chain.strikes if strike_min < strike < strike_max ] contracts = [ Option(qualified_contract.symbol, expiration, strike, right, qualified_contract.exchange, tradingClass=qualified_contract.symbol) for right in rights for expiration in expirations for strike in strikes ] if use_delayed_data: ib.reqMarketDataType(3) ib.qualifyContracts(*contracts) contracts = [contract for contract in contracts if contract.multiplier] if use_delayed_data: ib.reqMarketDataType(3) tickers = ib.reqTickers(*contracts) d = { "Expiration": [ str(ticker.contract.lastTradeDateOrContractMonth) for ticker in tickers ], "Strike": [ticker.contract.strike for ticker in tickers], "Right": [str(ticker.contract.right) for ticker in tickers], "Ask": [ticker.ask for ticker in tickers], "Multiplier": [int(ticker.contract.multiplier) for ticker in tickers], } return pd.DataFrame(data=d)
from ib_insync import IB, Option, Stock # For this example, must have TWS running ib = IB() ib.connect("127.0.0.1", 7497, clientId=1) ib.reqMarketDataType(4) # get SPY option chain symbol = "SPY" stock = Stock(symbol, "SMART", currency="USD") contracts = ib.qualifyContracts(stock) [ticker] = ib.reqTickers(stock) tickerValue = ticker.marketPrice() print(tickerValue) chains = ib.reqSecDefOptParams(stock.symbol, "", stock.secType, stock.conId) chain = next(c for c in chains if c.exchange == "SMART") print(chain) # get call options for all expirations and strikes within range strikes = [ strike for strike in chain.strikes if strike % 5 == 0 and tickerValue - 20 < strike < tickerValue + 20 ] contracts = [ Option(symbol, expiration, strike, "C", "SMART", tradingClass=chain.tradingClass) for expiration in chain.expirations
def main(symbol): # util.logToConsole(logging.DEBUG) util.logToFile('log.txt') s = symbol.upper() click.echo("Options for {} Loading: ".format(s), nl=False) ib = IB() ib.connect('127.0.0.1', 7497, clientId=3, readonly=True) contract = Stock(s, 'SMART', 'USD') ib.qualifyContracts(contract) click.echo('Chains ', nl=False) chains = ib.reqSecDefOptParams(contract.symbol, '', contract.secType, contract.conId) chain = next(c for c in chains if c.exchange == 'SMART') click.echo('Price '.format(s), nl=False) ib.reqMarketDataType(1) [ticker] = ib.reqTickers(contract) value = ticker.marketPrice() strikes = [ strike for strike in chain.strikes if value * 0.90 < strike < value * 1.0 ] expirations = sorted(exp for exp in chain.expirations)[:2] rights = ['P', 'C'] click.echo("Option Contracts {}@{} ".format(s, value), nl=False) contracts = [ Option(s, expiration, strike, right, 'SMART', tradingClass=s) for right in rights for expiration in expirations for strike in strikes ] click.echo('Validate ', nl=False) contracts = ib.qualifyContracts(*contracts) click.echo(len(contracts), nl=False) ib.reqMarketDataType(4) click.echo(' Ticker') tickers = ib.reqTickers(*contracts) options = [] for t in tickers: # click.echo(t) # calc = ib.calculateOptionPrice( # t.contract, volatility=0.14, underPrice=value) # print(calc) options.append(OptionData(t)) df = util.df(options, [ 'symbol', 'lastTradeDateOrContractMonth', 'strike', 'right', 'marketPrice', 'optionYield', 'timeToExpiration', 'spread', 'bid', 'ask', 'impliedVol', 'delta', 'gamma', 'vega' ]) click.echo(df) currentWeekPut = df[(df['right'] == 'P') & (df['lastTradeDateOrContractMonth'] == expirations[0])] click.echo(currentWeekPut.loc[(abs(abs(currentWeekPut.delta) - 0.2)).sort_values().index].head(2)) ib.disconnect()