def createContract(self, symbol, secType, currency, exchange, primaryExchange=None, right=None, strike=None, expiry=None): contract = Contract() if type(symbol) is list: # Foreign stocks print(symbol[0], symbol[1]) contract.symbol = symbol[0] contract.currency = symbol[1] else: contract.symbol = symbol contract.currency = currency if primaryExchange: contract.primaryExchange = primaryExchange contract.secType = secType contract.exchange = exchange if right: contract.right = right if strike: contract.strike = strike if expiry: contract.lastTradeDateOrContractMonth = expiry return contract
def make_contract(symbol, secType, exchange, primaryExchange, currency, lastTradeDateOrContractMonth=None, strike=None, right=None, multiplier=None, tradingClass=None): contract = Contract() contract.symbol = symbol contract.secType = secType contract.exchange = exchange contract.primaryExchange = primaryExchange contract.currency = currency if lastTradeDateOrContractMonth is not None: contract.lastTradeDateOrContractMonth = lastTradeDateOrContractMonth if strike is not None: contract.strike = strike if right is not None: contract.right = strike if multiplier is not None: contract.multiplier = multiplier if tradingClass is not None: contract.tradingClass = tradingClass return contract
def basic_order(self, order_id: int): contract_aapl = self.contract_aapl() parent = Order() parent.orderId = order_id parent.action = "buy" parent.orderType = "LMT" parent.totalQuantity = 1 parent.lmtPrice = 8 parent.transmit = False option_contract = Contract() option_contract.symbol = 'TSLA' option_contract.secType = "OPT" option_contract.exchange = "SMART" option_contract.primaryExchange = "SMART" option_contract.currency = "USD" option_contract.strike = 310.0 option_contract.lastTradeDateOrContractMonth = "20190315" option_contract.right = "P" pp33_order_builder = PP33BracketOrderBuilder(order_id, parent) for order_in_bracket in pp33_order_builder.bracket_order_list(): self.placeOrder(order_in_bracket.orderId, option_contract, order_in_bracket)
def processPositionDataMsg(self, fields): sMsgId = next(fields) version = decode(int, fields) account = decode(str, fields) # decode contract fields contract = Contract() contract.conId = decode(int, fields) contract.symbol = decode(str, fields) contract.secType = decode(str, fields) contract.lastTradeDateOrContractMonth = decode(str, fields) contract.strike = decode(float, fields) contract.right = decode(str, fields) contract.multiplier = decode(str, fields) contract.exchange = decode(str, fields) contract.currency = decode(str, fields) contract.localSymbol = decode(str, fields) if version >= 2: contract.tradingClass = decode(str, fields) if self.serverVersion >= MIN_SERVER_VER_FRACTIONAL_POSITIONS: position = decode(float, fields) else: position = decode(int, fields) avgCost = 0. if version >= 3: avgCost = decode(float, fields) self.wrapper.position(account, contract, position, avgCost)
def processPositionMultiMsg(self, fields): sMsgId = next(fields) version = decode(int, fields) reqId = decode(int, fields) account = decode(str, fields) # decode contract fields contract = Contract() contract.conId = decode(int, fields) contract.symbol = decode(str, fields) contract.secType = decode(str, fields) contract.lastTradeDateOrContractMonth = decode(str, fields) contract.strike = decode(float, fields) contract.right = decode(str, fields) contract.multiplier = decode(str, fields) contract.exchange = decode(str, fields) contract.currency = decode(str, fields) contract.localSymbol = decode(str, fields) contract.tradingClass = decode(str, fields) position = decode(float, fields) avgCost = decode(float, fields) modelCode = decode(str, fields) self.wrapper.positionMulti(reqId, account, modelCode, contract, position, avgCost)
def make_contract(symbol='', conID=0, secType='STK', currency='USD', exchange='', primaryExchange='', multiplier=100, tradingClass='', localSymbol='', right='', lastTradeDateOrContractMonth='', strike=0): contract = Contract() contract.symbol = symbol contract.conId = conID contract.secType = secType contract.currency = currency contract.exchange = exchange contract.primaryExchange = primaryExchange contract.multiplier = multiplier contract.tradingClass = tradingClass if tradingClass == '': contract.tradingClass = symbol contract.localSymbol = localSymbol contract.right = right contract.lastTradeDateOrContractMonth = lastTradeDateOrContractMonth contract.strike = strike return contract
def generate_ib_contract(symbol: str, exchange: Exchange) -> Optional[Contract]: """""" try: fields = symbol.split(JOIN_SYMBOL) ib_contract = Contract() ib_contract.exchange = EXCHANGE_VT2IB[exchange] ib_contract.secType = fields[-1] ib_contract.currency = fields[-2] ib_contract.symbol = fields[0] if ib_contract.secType in ["FUT", "OPT", "FOP"]: ib_contract.lastTradeDateOrContractMonth = fields[1] if ib_contract.secType == "FUT": if len(fields) == 5: ib_contract.multiplier = int(fields[2]) if ib_contract.secType in ["OPT", "FOP"]: ib_contract.right = fields[2] ib_contract.strike = float(fields[3]) ib_contract.multiplier = int(fields[4]) except IndexError: ib_contract = None return ib_contract
def processExecutionDataMsg(self, fields): sMsgId = next(fields) version = decode(int, fields) reqId = -1 if version >= 7: reqId = decode(int, fields) orderId = decode(int, fields) # decode contract fields contract = Contract() contract.conId = decode(int, fields) # ver 5 field contract.symbol = decode(str, fields) contract.secType = decode(str, fields) contract.lastTradeDateOrContractMonth = decode(str, fields) contract.strike = decode(float, fields) contract.right = decode(str, fields) if version >= 9: contract.multiplier = decode(str, fields) contract.exchange = decode(str, fields) contract.currency = decode(str, fields) contract.localSymbol = decode(str, fields) if version >= 10: contract.tradingClass = decode(str, fields) # decode execution fields exec = Execution() exec.orderId = orderId exec.execId = decode(str, fields) exec.time = decode(str, fields) exec.acctNumber = decode(str, fields) exec.exchange = decode(str, fields) exec.side = decode(str, fields) if self.serverVersion >= MIN_SERVER_VER_FRACTIONAL_POSITIONS: exec.shares = decode(float, fields) else: exec.shares = decode(int, fields) exec.price = decode(float, fields) exec.permId = decode(int, fields) # ver 2 field exec.clientId = decode(int, fields) # ver 3 field exec.liquidation = decode(int, fields) # ver 4 field if version >= 6: exec.cumQty = decode(float, fields) exec.avgPrice = decode(float, fields) if version >= 8: exec.orderRef = decode(str, fields) if version >= 9: exec.evRule = decode(str, fields) exec.evMultiplier = decode(float, fields) if self.serverVersion >= MIN_SERVER_VER_MODELS_SUPPORT: exec.modelCode = decode(str, fields) self.wrapper.execDetails(reqId, contract, exec)
def contract_amzn_opt(self): incomplete_contract = Contract() incomplete_contract.symbol = 'AMZN' incomplete_contract.secType = "OPT" incomplete_contract.exchange = "SMART" incomplete_contract.currency = "USD" incomplete_contract.strike = 1900 incomplete_contract.lastTradeDateOrContractMonth = "20190719" incomplete_contract.right = "C" return incomplete_contract
def contract_spx_option(self): contract = Contract() contract.symbol = 'SPX' contract.secType = "OPT" contract.exchange = "SMART" contract.primaryExchange = "SMART" contract.currency = "USD" contract.strike = 2800 contract.lastTradeDateOrContractMonth = "20190329" contract.right = "C" return contract
def createOptionContract(self, symbol, currency, exchange): contract = Contract() contract.symbol = symbol contract.secType = "OPT" contract.exchange = exchange contract.currency = currency contract.lastTradeDateOrContractMonth = "201901" contract.strike = 150 contract.right = "C" contract.multiplier = "100" return contract
def OptionAtIse(): contract = Contract() contract.symbol = "BPX" contract.secType = "OPT" contract.currency = "USD" contract.exchange = "ISE" contract.lastTradeDateOrContractMonth = "20160916" contract.right = "C" contract.strike = 65 contract.multiplier = "100" return contract
def OptionAtBOX(): contract = Contract() contract.symbol = "GOOG" contract.secType = "OPT" contract.exchange = "BOX" contract.currency = "USD" contract.lastTradeDateOrContractMonth = "20170120" contract.strike = 615 contract.right = "C" contract.multiplier = "100" return contract
def FuturesOnOptions(): contract = Contract() contract.symbol = "SPX" contract.secType = "FOP" contract.exchange = "GLOBEX" contract.currency = "USD" contract.lastTradeDateOrContractMonth = "20180315" contract.strike = 1025 contract.right = "C" contract.multiplier = "250" return contract
def optContract(): contract = Contract() contract.symbol = 'GOOG' contract.secType = 'OPT' contract.exchange = 'SMART' contract.currency = 'USD' contract.lastTradeDateOrContractMonth = '20190823' contract.strike = 1190 contract.right = 'C' contract.multiplier = '100' return contract
def form_option_contract(symbol, strike, type): contract1 = Contract() # Creates a contract object from the import contract1.symbol = symbol # Sets the ticker symbol contract1.secType = "OPT" # Defines the security type as stock contract1.currency = "USD" # Currency is US dollars contract1.exchange = "SMART" contract1.strike = strike contract1.right = type # call not put contract1.expiry = "20200717" contract1.lastTradeDateOrContractMonth = "20200717" # contract1.PrimaryExch = "NYSE" return contract1 # Returns the contract object
def OptionWithTradingClass(): contract = Contract() contract.symbol = "SPX" contract.secType = "OPT" contract.exchange = "SMART" contract.primaryExchange = "SMART" contract.currency = "USD" contract.lastTradeDateOrContractMonth = "20190219" contract.strike = 2520 contract.right = "C" contract.multiplier = "100" contract.tradingClass = "SPX" return contract
def OptionAtBOX(): #! [optcontract] contract = Contract() contract.symbol = "AMZN" contract.secType = "OPT" contract.exchange = "SMART" contract.currency = "USD" contract.lastTradeDateOrContractMonth = "20190125" contract.strike = 1570 contract.right = "C" contract.multiplier = "100" #! [optcontract] return contract
def getRolledOption(self, r): option = Contract() option.symbol = self.statData.buyWrite["underlyer"]["@tickerSymbol"] option.avPrice = r["sellprice"] option.secType = "OPT" option.exchange = "SMART" option.currency = "USD" option.lastTradeDateOrContractMonth = r['to'] option.strike = r['strike'] option.right = "Call" option.multiplier = "100" return option
def option(self): option = Contract() option.symbol = self.statData.buyWrite["underlyer"]["@tickerSymbol"] option.avPrice = self.statData.inioptprice option.secType = "OPT" option.exchange = "SMART" option.currency = "USD" option.lastTradeDateOrContractMonth = self.statData.expiry option.strike = self.statData.strike option.right = "Call" option.multiplier = "100" return option
def contract_bidu_option(self): # ! [optcontract] contract = Contract() contract.symbol = "BIDU" contract.secType = "OPT" contract.exchange = "SMART" contract.currency = "USD" contract.lastTradeDateOrContractMonth = "20190322" contract.strike = 165 contract.right = "PUT" contract.multiplier = "100" # ! [optcontract] return contract
def OptionWithTradingClass(): # ! [optcontract_tradingclass] contract = Contract() contract.symbol = "SANT" contract.secType = "OPT" contract.exchange = "MEFFRV" contract.currency = "EUR" contract.lastTradeDateOrContractMonth = "20190621" contract.strike = 7.5 contract.right = "C" contract.multiplier = "100" contract.tradingClass = "SANEU" # ! [optcontract_tradingclass] return contract
def make_contract(symbol: str, sec_type: str, currency: str, exchange: str, expiry: str, strike: str) -> Contract: contract = Contract() contract.symbol = symbol contract.secType = sec_type contract.currency = currency if sec_type == "OPT": contract.lastTradeDateOrContractMonth = expiry contract.strike = strike contract.right = "Call" contract.multiplier = "100" contract.exchange = exchange return contract
def Dict_to_Contract(data: dict): con = Contract() con.symbol = data['symbol'] con.conId = data['conID'] con.secType = data['secType'] con.currency = data['currency'] con.exchange = data['exchange'] con.primaryExchange = data['primaryExchange'] con.multiplier = data['multiplier'] con.tradingClass = data['tradingClass'] con.localSymbol = data['localSymbol'] con.right = data['right'] con.lastTradeDateOrContractMonth = data['lastTradeDateOrContractMonth'] con.strike = data['strike'] return con
def main(): SetupLogger() logging.info("now is %s", datetime.datetime.now()) openPosition = getOpenPosition() print(openPosition) app = TestApp(ib_api_include.ip, ib_api_include.port, ib_api_include.clientId) time.sleep(ib_api_include.sleeptime_trading) summary = DataFrame(portfolio, columns=[ 'symbol', 'secType', 'exchange', 'position', 'marketPrice', 'marketValue', 'averageCost', 'unrealizedPNL', 'realizedPNL', 'accountName' ]) reqId = 1000 #watchlist_stock_treshold = pd.read_excel('my_ib_threshold.xlsx', sheet_name = 'watchlist_stock_treshold') #watchlist_stock_treshold = DataFrame(watchlist_stock_treshold) for i in range(0, len(openPosition)): record = openPosition.iloc[i] ibcontract = IBcontract() ibcontract.secType = record.AssetClass ibcontract.symbol = record.UnderlyingSymbol ibcontract.exchange = "SMART" ibcontract.currency = record.CurrencyPrimary ibcontract.lastTradeDateOrContractMonth = record.Expiry ibcontract.strike = record.Strike ibcontract.multiplier = record.Multiplier ibcontract.right = record["Put/Call"] app.reqMktData(reqId, ibcontract) ibcontract = IBcontract() ibcontract.symbol = "MU" ibcontract.exchange = "SMART" ibcontract.secType = "STK" app.reqMktNews(reqId, ibcontract) time.sleep(30) print( DataFrame(marketdataPrice, columns=[ "reqId", "tickType", "tickPrice", "CanAutoExecuteOrNot" ])) print( DataFrame(marketdataSize, columns=["reqId", "tickType", "tickSize"])) reqId += 1 app.disconnect()
def read_option_chain(MainClass, ScannerClass, ticker): # Define a contract for the underlying stock contract = Contract() contract.symbol = ticker contract.secType = 'STK' contract.exchange = 'SMART' contract.currency = 'USD' MainClass.reqContractDetails(0, contract) time.sleep(2) # Get the current price of the stock MainClass.reqTickByTickData(1, contract, "MidPoint", 1, True) time.sleep(4) # Request strike prices and expirations Scannerclass = client if Scannerclass.conids: Scannerclass.reqSecDefOptParams(2, ticker, '', 'STK', Scannerclass.conid) time.sleep(2) else: print('Failed to obtain contract identifier.') exit() # Create contract for stock option req_id = 3 if Scannerclass.strikes: for strike in Scannerclass.strikes: Scannerclass.chain[strike] = {} for right in ['C', 'P']: # Add to the option chain Scannerclass.chain[strike][right] = {} # Define the option contract contract.secType = 'OPT' contract.right = right contract.strike = strike contract.exchange = Scannerclass.exchange contract.lastTradeDateOrContractMonth = Scannerclass.expiration # Request option data Scannerclass.reqMktData(req_id, contract, '100', False, False, []) req_id += 1 time.sleep(1)
def createCallOpt(symbol, strike, contractMonth, sec_type="OPT", currency="INR", exchange="NSE"): contract = Contract() contract.symbol = symbol contract.secType = sec_type contract.currency = currency contract.exchange = exchange contract.right = "C" contract.strike = strike contract.multiplier = 1 contract.tradingClass = 'BANKNIFTY' contract.lastTradeDateOrContractMonth = contractMonth return contract
def create_options_contract(symbol, exp, strike, right, exchange='SMART', currency='USD', multiplier='100'): # opt_spy = create_options_contract('SPY', '20210319', '400', 'C') contract = Contract() contract.symbol = symbol contract.lastTradeDateOrContractMonth = exp contract.strike = strike contract.right = right contract.secType = 'OPT' contract.exchange = exchange contract.currency = currency contract.multiplier = multiplier return contract
def processPortfolioValueMsg(self, fields): sMsgId = next(fields) version = decode(int, fields) # read contract fields contract = Contract() contract.conId = decode(int, fields) # ver 6 field contract.symbol = decode(str, fields) contract.secType = decode(str, fields) contract.lastTradeDateOrContractMonth = decode(str, fields) contract.strike = decode(float, fields) contract.right = decode(str, fields) if version >= 7: contract.multiplier = decode(str, fields) contract.primaryExchange = decode(str, fields) contract.currency = decode(str, fields) contract.localSymbol = decode(str, fields) # ver 2 field if version >= 8: contract.tradingClass = decode(str, fields) if self.serverVersion >= MIN_SERVER_VER_FRACTIONAL_POSITIONS: position = decode(float, fields) else: position = decode(int, fields) marketPrice = decode(float, fields) marketValue = decode(float, fields) averageCost = decode(float, fields) # ver 3 field unrealizedPNL = decode(float, fields) # ver 3 field realizedPNL = decode(float, fields) # ver 3 field accountName = decode(str, fields) # ver 4 field if version == 6 and self.serverVersion == 39: contract.primaryExchange = decode(str, fields) self.wrapper.updatePortfolio( contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accountName)
def _get_option_contract(ticker: str, expiration: str, strike: float, right: str, exchange="SMART", currency="USD", **_): """ Helper function for creating a contract object for use in querying data for options """ if right not in ["C", "P"]: raise ValueError(f"Invalid right: {right}") contract = Contract() contract.secType = "OPT" contract.symbol = ticker contract.exchange = exchange contract.currency = currency contract.lastTradeDateOrContractMonth = expiration contract.strike = strike contract.right = right return contract