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
class BrokerConnection(metaclass=Singleton): def __init__(self): self.ib = IB() def connect(self, host, port, client_id, callback=None): self.ib.connect(host, port, clientId=client_id) if callback: self.ib.connectedEvent += callback def disconnect(self): self.ib.disconnect() def isConnected(self): return self.ib.isConnected() def positions(self): return [ pos for pos in self.ib.positions() if pos.contract.secType == 'OPT' ] def reqMatchingSymbols(self, text_to_search): ''' Function IBApi::EClient::reqMatchingSymbols is available to search for stock contracts. The input can be either the first few letters of the ticker symbol, or for longer strings, a character sequence matching a word in the security name. https://interactivebrokers.github.io/tws-api/matching_symbols.html ''' return self.ib.reqMatchingSymbols(text_to_search) def getOptionChainContracts(self, contract): chain = self.ib.reqSecDefOptParams(contract.symbol, contract.exchange, contract.secType, contract.conId) qChain = self.ib.qualifyContracts(chain) #return util.df(qChain) return qChain
class Window(qt.QWidget): def __init__(self, host, port, clientId): qt.QWidget.__init__(self) self.vxxbLabel = qt.QLabel('VXXB') self.vxxbButton = qt.QPushButton('VXXB') self.tltLabel = qt.QLabel('TLT') self.tltButton = qt.QPushButton('TLT') self.gldLabel = qt.QLabel('GLD') self.gldButton = qt.QPushButton('GLD') self.vxxbButton.clicked.connect(self.onVXXBButtonClicked) self.gldButton.clicked.connect(self.onGLDButtonClicked) self.tltButton.clicked.connect(self.onTLTButtonClicked) self.pricedic = {} # 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.QGridLayout(self)#qt.QVBoxLayout(self) layout.addWidget(self.vxxbLabel,0,0,1,2) layout.addWidget(self.vxxbButton,1,0,1,2) layout.addWidget(self.tltLabel,0,2,1,2) layout.addWidget(self.tltButton,1,2,1,2) layout.addWidget(self.gldLabel,0,4,1,2) layout.addWidget(self.gldButton,1,4,1,2) # layout.addWidget(self.edit) layout.addWidget(self.table,2,0,6,6) layout.addWidget(self.connectButton,9,2,1,2) self.connectInfo = (host, port, clientId) self.ib = IB() self.ib.pendingTickersEvent += self.table.onPendingTickers self.ib.pendingTickersEvent += self.onPendingTickersForLabels def add(self, contract): 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) def onConnectButtonClicked(self, _): if self.ib.isConnected(): self.ib.disconnect() self.table.clearTickers() self.connectButton.setText('Connect') else: self.ib.connect(*self.connectInfo) self.connectButton.setText('Disonnect') self.vxxb = Stock('VXXB',exchange='SMART') self.ib.qualifyContracts(self.vxxb) self.table.vxxbticker = self.ib.reqMktData(self.vxxb, '', False, False, None) self.tlt = Stock('TLT',exchange='ARCA') self.ib.qualifyContracts(self.tlt) self.table.tltticker = self.ib.reqMktData(self.tlt, '', False, False, None) self.gld = Stock('GLD',exchange='ARCA') self.ib.qualifyContracts(self.gld) self.table.gldticker = self.ib.reqMktData(self.gld, '', False, False, None) def closeEvent(self, ev): asyncio.get_event_loop().stop() def onPendingTickersForLabels(self, tickers): for ticker in tickers: if type(getattr(ticker,'contract'))==Stock: if ticker.contract.symbol=='VXXB': self.vxxbprice = ticker.marketPrice() self.vxxbLabel.setText('{0:0.2f}'.format(self.vxxbprice)) self.table.vxxbprice = self.vxxbprice self.pricedic['VXXB'] = self.vxxbprice # print('vxxb:'+str(ticker.marketPrice())) elif ticker.contract.symbol=='GLD': self.gldprice = ticker.marketPrice() self.gldLabel.setText('{0:0.2f}'.format(self.gldprice)) self.table.gldprice=self.gldprice self.pricedic['GLD'] = self.gldprice # print('gld:'+str(ticker.marketPrice())) else: self.tltprice = ticker.marketPrice() self.tltLabel.setText('{0:0.2f}'.format(self.tltprice)) self.table.tltprice=self.tltprice self.pricedic['TLT'] = self.tltprice # print('tlt:'+str(ticker.marketPrice())) def prepareOptionContract(self,stockcontract): contractPrice = self.pricedic[stockcontract.symbol] chains = self.ib.reqSecDefOptParams(stockcontract.symbol, '', stockcontract.secType,stockcontract.conId) chain = next(c for c in chains if c.exchange == 'SMART') # print(chain) strikes = sorted([strike for strike in chain.strikes if contractPrice - 2 < strike < contractPrice + 2]) expirations = sorted(exp for exp in chain.expirations)[:2] contracts = [Option(stockcontract.symbol, expiration, strike, 'P','SMART') for expiration in expirations for strike in strikes] # print(contracts) self.ib.qualifyContracts(*contracts) for ac in contracts: self.add(contract=ac) def onVXXBButtonClicked(self, _): if self.ib.isConnected(): self.table.clearTickers() self.prepareOptionContract(self.vxxb) self.table.symbolofticker = 'VXXB' def onGLDButtonClicked(self, _): if self.ib.isConnected(): self.table.clearTickers() self.prepareOptionContract(self.gld) self.table.symbolofticker = 'GLD' def onTLTButtonClicked(self, _): print('TLT') if self.ib.isConnected(): self.table.clearTickers() self.prepareOptionContract(self.tlt) self.table.symbolofticker = 'TLT'
class trade_ES(): def __init__(self): self.ib = IB() self.ib.connect('127.0.0.1', 7497, clientId=np.random.randint(10, 1000)) self.tickers_ret = {} self.endDateTime = '' self.No_days = '43200 S' self.interval = '30 secs' self.tickers_signal = "Hold" self.ES = Future(symbol='ES', lastTradeDateOrContractMonth='20200619', exchange='GLOBEX', currency='USD') self.ib.qualifyContracts(self.ES) self.ES_df = self.ib.reqHistoricalData(contract=self.ES, endDateTime=self.endDateTime, durationStr=self.No_days, barSizeSetting=self.interval, whatToShow='TRADES', useRTH=False, keepUpToDate=True) self.tickers_ret = [] self.options_ret = [] self.option = {'call': FuturesOption, 'put': FuturesOption} self.options_history = {} self.trade_options = {'call': [], 'put': []} self.price = 0 self.i = -1 self.ES_df.updateEvent += self.make_clean_df self.Buy = True self.Sell = False self.ib.positionEvent += self.order_verify self.waitTimeInSeconds = 220 self.tradeTime = 0 self.mySemaphore = asyncio.Semaphore(1) def run(self): self.make_clean_df(self.ES_df) def next_exp_weekday(self): weekdays = {2: [6, 0], 4: [0, 1, 2], 0: [3, 4]} today = datetime.date.today().weekday() for exp, day in weekdays.items(): if today in day: return exp def next_weekday(self, d, weekday): days_ahead = weekday - d.weekday() if days_ahead <= 0: # Target day already happened this week days_ahead += 7 date_to_return = d + datetime.timedelta( days_ahead) # 0 = Monday, 1=Tuself.ESday, 2=Wednself.ESday... return date_to_return.strftime('%Y%m%d') def get_strikes_and_expiration(self): expiration = self.next_weekday(datetime.date.today(), self.next_exp_weekday()) chains = self.ib.reqSecDefOptParams(underlyingSymbol='ES', futFopExchange='GLOBEX', underlyingSecType='FUT', underlyingConId=self.ES.conId) chain = util.df(chains) strikes = chain[chain['expirations'].astype(str).str.contains( expiration)].loc[:, 'strikes'].values[0] [ESValue] = self.ib.reqTickers(self.ES) ES_price = ESValue.marketPrice() strikes = [ strike for strike in strikes if strike % 5 == 0 and ES_price - 10 < strike < ES_price + 10 ] return strikes, expiration def get_contract(self, right, net_liquidation): strikes, expiration = self.get_strikes_and_expiration() for strike in strikes: contract = FuturesOption(symbol='ES', lastTradeDateOrContractMonth=expiration, strike=strike, right=right, exchange='GLOBEX') self.ib.qualifyContracts(contract) self.price = self.ib.reqMktData(contract, "", False, False) if float(self.price.last) * 50 >= net_liquidation: continue else: return contract def make_clean_df(self, ES_df, hashbar=None): ES_df = util.df(ES_df) ES_df['RSI'] = ta.RSI(ES_df['close']) ES_df['macd'], ES_df['macdsignal'], ES_df['macdhist'] = ta.MACD( ES_df['close'], fastperiod=12, slowperiod=26, signalperiod=9) ES_df['MA_9'] = ta.MA(ES_df['close'], timeperiod=9) ES_df['MA_21'] = ta.MA(ES_df['close'], timeperiod=21) ES_df['MA_200'] = ta.MA(ES_df['close'], timeperiod=200) ES_df['EMA_9'] = ta.EMA(ES_df['close'], timeperiod=9) ES_df['EMA_21'] = ta.EMA(ES_df['close'], timeperiod=21) ES_df['EMA_200'] = ta.EMA(ES_df['close'], timeperiod=200) ES_df['ATR'] = ta.ATR(ES_df['high'], ES_df['low'], ES_df['close']) ES_df['roll_max_cp'] = ES_df['high'].rolling(20).max() ES_df['roll_min_cp'] = ES_df['low'].rolling(20).min() ES_df['roll_max_vol'] = ES_df['volume'].rolling(20).max() ES_df.dropna(inplace=True) self.loop_function(ES_df) def placeOrder(self, contract, order): trade = self.ib.placeOrder(contract, order) tradeTime = datetime.datetime.now() return ([trade, contract, tradeTime]) def sell(self, contract, position): self.ib.qualifyContracts(contract) if position.position > 0: order = 'Sell' else: order = 'Buy' marketorder = MarketOrder(order, abs(position.position)) marketTrade, contract, tradeTime = self.placeOrder( contract, marketorder) while self.ib.position.position != 0: self.ib.sleep(1) self.mySemaphore.release() async def buy(self, contract): await self.semaphore.acquire() self.ib.qualifyContracts(contract) marketorder = MarketOrder('Buy', 1) marketTrade = self.ib.placeOrder(contract, marketorder) def order_verify(self, order): if order.position == 0.0 or order.position < 0: self.Buy = True self.Sell = False elif order.position > 0: self.Buy = False self.Sell = True else: self.Buy = False self.Sell = False print(f'Buy= {self.Buy}, sell = {self.Sell}') def loop_function(self, ES_df): df = ES_df[[ 'high', 'low', 'volume', 'close', 'RSI', 'ATR', 'roll_max_cp', 'roll_min_cp', 'roll_max_vol', 'EMA_9', 'EMA_21', 'macd', 'macdsignal' ]] if self.tickers_signal == "Hold": print('Hold') if df["high"].iloc[self.i] >= df["roll_max_cp"].iloc[self.i] and \ df["volume"].iloc[self.i] > df["roll_max_vol"].iloc[self.i - 1] and df['RSI'].iloc[self.i] > 30 \ and df['macd'].iloc[self.i] > df['macdsignal'].iloc[self.i] : self.tickers_signal = "Buy" return elif df["low"].iloc[self.i] <= df["roll_min_cp"].iloc[self.i] and \ df["volume"].iloc[self.i] > df["roll_max_vol"].iloc[self.i - 1] and df['RSI'].iloc[self.i] < 70 \ and df['macd'].iloc[self.i] < df['macdsignal'].iloc[self.i]: self.tickers_signal = "Sell" return else: self.tickers_signal = "Hold" return elif self.tickers_signal == "Buy": print('BUY SIGNAL') if df["close"].iloc[self.i] > df["close"].iloc[self.i - 1] - ( 0.75 * df["ATR"].iloc[self.i - 1]) and len( self.ib.positions()) != 0: print( f'{df["close"].iloc[self.i]} > {df["close"].iloc[self.i - 1] - (0.75 * df["ATR"].iloc[self.i - 1])}' ) print('first buy condition') positions = self.ib.positions() for position in positions: if position.contract.right == 'C': self.sell(position.contract, position) self.tickers_signal = "Hold" return elif df["low"].iloc[self.i] <= df["roll_min_cp"].iloc[self.i] and \ df["volume"].iloc[self.i] > df["roll_max_vol"].iloc[self.i - 1] and df['RSI'].iloc[self.i] < 70 \ and df['macd'].iloc[self.i] < df['macdsignal'].iloc[self.i] and len(self.ib.positions())!=0: self.tickers_signal = "Sell" print('sell') positions = self.ib.positions() for position in positions: if position.contract.right == 'C': self.sell(position.contract, position) self.tickers_signal == "Sell" return else: if len(self.ib.positions()) == 0: self.option['call'] = self.get_contract( right="C", net_liquidation=2000) self.buy(self.option['call']) self.tickers_signal = "Hold" else: self.tickers_signal = "Hold" elif self.tickers_signal == "Sell": print('SELL SIGNAL') if df["close"].iloc[self.i] < df["close"].iloc[self.i - 1] + ( 0.75 * df["ATR"].iloc[self.i - 1]) and len( self.ib.positions()) != 0: print('first sell condition') print( f'{df["close"].iloc[self.i]} < {df["close"].iloc[self.i - 1] - (0.75 * df["ATR"].iloc[self.i - 1])}' ) print('sell') positions = self.ib.positions() for position in positions: if position.contract.right == 'P': self.sell(position.contract, position) self.tickers_signal = "Hold" return elif df["high"].iloc[self.i] >= df["roll_max_cp"].iloc[self.i] and \ df["volume"].iloc[self.i] > df["roll_max_vol"].iloc[self.i - 1] and df['RSI'].iloc[self.i] > 30 \ and df['macd'].iloc[self.i] > df['macdsignal'].iloc[self.i] and len(self.ib.positions())!=0: self.tickers_signal = "Buy" print('sell') positions = self.ib.positions() for position in positions: if position.contract.right == 'P': self.sell(position.contract, position) self.tickers_signal == "Buy" return else: if len(self.ib.positions()) == 0: self.option['put'] = self.get_contract( right="P", net_liquidation=2000) self.buy(self.option['put']) self.tickers_signal = "Hold" else: self.tickers_signal = "Hold" def checkError(self, errCode, errString): print('Error Callback', errCode, errString) if errCode == 2104: print('re-connect after 5 secs') self.ib.sleep(5) self.ib.disconnect() self.ib.connect('127.0.0.1', 7497, clientId=np.random.randint(10, 1000)) self.make_clean_df(self.ES)
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()
A sale's also a buy. How the f**k do I distinguish that shit? Focus only on opts transacted at the ask. Probably Δ hedged by the writer. What about Γ? EOD? """ ib = IB() ib.connect("127.0.0.1", 4002, clientId=2) # TWS=7496, GTW=4001, # PAPER=7497 cs = ib.reqContractDetails(Stock(symbol="SPY", exchange="ARCA")) x = cs[0].contract # 1) prendi tutti gli strikes e tutte le exp chains = ib.reqSecDefOptParams( underlyingSymbol=x.symbol, futFopExchange="", underlyingSecType=x.secType, underlyingConId=x.conId, ) chain = next(c for c in chains if c.tradingClass == "SPY" and c.exchange == "SMART") [ticker] = ib.reqTickers(x) xValue = ticker.marketPrice() strikes = [ strike for strike in chain.strikes if strike % 5 == 0 and xValue - 2 < strike < xValue + 2 ] expirations = sorted(exp for exp in chain.expirations)[:3] rights = ["P", "C"]