def historical_from_ib(directory: str, data_range): directory = os.path.abspath(directory) if not os.path.exists(directory): os.makedirs(directory) print('Root directory "%s" has been created.' % directory) else: print('Root directory "%s" already exists.' % directory) tws = TwsClient(client_id=CLIENT_ID) with tws.connect(): hsi = Contract() hsi.exchange = "HKFE" hsi.secType = "IND" hsi.symbol = "HSI" hsi.currency = "HKD" hhi = Contract() hhi.exchange = "HKFE" hhi.secType = "IND" hhi.symbol = "HHI.HK" hhi.currency = "HKD" for the_date in data_range: store_file(directory, tws, the_date, hsi) store_file(directory, tws, the_date, hhi)
def createContract(self, ticker, secType): contract = Contract() contract.exchange = "SMART" # Default exchange, IB routing algo contract.symbol = ticker contract.secType = secType contract.currency = "USD" return contract
def get_contract_by_sid(self, sid): contract = Contract() contract.symbol = sid contract.secType = 'STK' contract.exchange = 'SMART' contract.currency = 'USD' return contract
def createContract(self, secType, symbol, exchange, expiry=None, currency=None): """ Create new IB Contract :param secType: Contract sector type: STK, OPT, FUT, IND, FOP, CASH,BAG, NEWS :param expiry: The expiration date. Use the format YYYYMM. :param symbol: This is the symbol of the underlying asset. :param exchange: The order destination, such as Smart. """ ibcontract = IBcontract() ibcontract.secType = secType if expiry: ibcontract.expiry = expiry if currency: ibcontract.currency = currency ibcontract.symbol = symbol ibcontract.exchange = exchange return ibcontract
def run(self): # Simple contract for GOOG contract = Contract() #contract.conId = 114376112 contract.exchange = "SMART" contract.symbol = "ATK" contract.secType = "STK" #contract.right = "PUT" contract.currency = "USD" #contract.secType = 'OPT' #contract.strike = 24 #contract.expiry = '20121116' today = datetime.today() order = Order() order.orderId = 89 order.clientId = 44 order.action = "BUY" order.totalQuantity = 1 # may have to calculate a smarter number order.orderType = "MKT" order.tif = "DAY" order.transmit = True order.sweepToFill = True order.outsideRth = True contract.symbol = "alkjdf" self.callback.askPrice = None self.tws.reqMktData(2, contract, "", 1) max_wait = timedelta(seconds=30) + datetime.now() while self.callback.askPrice is None: if datetime.now() > max_wait: print "max wait giving up" break print self.callback.askPrice
def main(): """ This simple example returns historical data """ callback = IBWrapper() client = IBclient(callback) ibcontract = IBcontract() ibcontract.secType = "FUT" ibcontract.expiry = "202009" ibcontract.symbol = "GE" ibcontract.exchange = "GLOBEX" # ibcontract.secType = "STK" # ibcontract.exchange = "SMART" # ibcontract.symbol = "MMM" # ibcontract.currency = "USD" end_dt = datetime.datetime(2016, 8, 3) ans = client.get_IB_historical_data(ibcontract, durationStr='5 d', barSizeSetting='5 mins', end_dt=end_dt) return ans
def create_contract(self): # Simple contract for GOOG contract = Contract() contract.exchange = "SMART" contract.symbol = "GOOG" contract.secType = "STK" contract.currency = "USD" return contract
def subscribe_to_market_data(self, symbol, exchange, sec_type, currency): c = Contract() c.symbol = symbol c.secType = sec_type c.exchange = exchange c.currency = currency self.reqMktData(self._ewrapper.next_ticker_id, c, "", False, None) self._ewrapper.ticker_symbol_dict[self._ewrapper.next_ticker_id] = symbol self._ewrapper.next_ticker_id += 1 self._ewrapper.symbol_contract_dict[symbol] = c
def dbcontract_to_ibcontract(dbcontract): symbol = str(dbcontract.sym) localSym = str(dbcontract.local_sym) if str(dbcontract.secType) == 'CASH': symbol = str(dbcontract.sym) + str(dbcontract.cur) if str(dbcontract.secType) == 'FUT': year = str(dbcontract.contractMonth)[0:4] mon = str(dbcontract.contractMonth)[4:6] addSym = '' print symbol, year, int(mon) if int(mon) == 1: addSym = 'F' print addSym if int(mon) == 2: addSym = 'G' if int(mon) == 3: addSym = 'H' if int(mon) == 4: addSym = 'J' if int(mon) == 5: addSym = 'K' if int(mon) == 6: addSym = 'M' if int(mon) == 7: addSym = 'N' if int(mon) == 8: addSym = 'Q' if int(mon) == 9: addSym = 'U' if int(mon) == 10: addSym = 'V' if int(mon) == 11: addSym = 'X' if int(mon) == 12: addSym = 'Z' addSym += year[3:4] print addSym localSym += addSym print 'Found', localSym contract = Contract() contract.symbol = str(symbol) contract.secType = str(dbcontract.secType) contract.exchange = str(dbcontract.exch) contract.primaryExchange = str(dbcontract.exch) contract.currency = str(dbcontract.cur) contract.expiry = str(dbcontract.expiry) #contract.strike= # Strike Price contract.localSymbol = localSym return contract
def subscribe_to_market_data(self, symbol, exchange, sec_type, currency): c = Contract() c.symbol = symbol c.secType = sec_type c.exchange = exchange c.currency = currency self.reqMktData(self._ewrapper.next_ticker_id, c, "", False, None) self._ewrapper.ticker_symbol_dict[ self._ewrapper.next_ticker_id] = symbol self._ewrapper.next_ticker_id += 1 self._ewrapper.symbol_contract_dict[symbol] = c
def create_contract(security): if security.split('.')[0]=='FUT': contract = Contract() contract.symbol = security.split('.')[1] contract.secType = 'FUT' contract.exchange = 'GLOBEX' contract.currency = security.split('.')[2] contract.expiry= security.split('.')[3] contract.primaryExchange='GLOBEX' elif security.split('.')[0]=='CASH': contract = Contract() contract.symbol = security.split('.')[1] contract.secType = 'CASH' contract.exchange = 'IDEALPRO' contract.currency = security.split('.')[2] contract.primaryExchange='IDEALPRO' elif security.split('.')[0]=='STK': contract = Contract() contract.symbol = security.split('.')[1] contract.secType = 'STK' contract.exchange = 'SMART' contract.currency = 'USD' contract.primaryExchange='SMART' return contract
def get_last_hist_data(client, symbols, startDate, endDate = datetime.datetime.now()): ibcontract = IBcontract() #ibcontract.secType = "FUT" #ibcontract.expiry="201809" #ibcontract.symbol="GE" #ibcontract.exchange="GLOBEX" ibcontract.secType = 'STK' ibcontract.exchange = 'SMART' ibcontract.currency = 'USD' ibcontract.primaryExchange = 'SMART' for index in range(len(symbols)): symbol = symbols[index] ibcontract.symbol = symbol lastDate = endDate while (cmp(startDate, lastDate) < 0): curDay = lastDate + datetime.timedelta(days = -28) print symbol, curDay, lastDate sdatetime=lastDate.strftime("%Y%m%d %H:%M:%S %Z") ans=client.get_IB_historical_data(ibcontract, sdatetime, '4 W', '1 hour', index) lastDate = curDay time.sleep(1) print "orglen: ", len(ans) ans = ans.drop_duplicates(subset=['symbol', 'sdate']) print "endlen: ", len(ans) ans.to_csv(symbol+".csv") #print ans conn=MySQLdb.connect(host='127.0.0.1',user='******',passwd='border', db='finance', port=3306) cur=conn.cursor() values=[] header = 'insert into stock_data_1hour(`symbol`, `sdate`, `open`, `high`, `low`, `close`, `volume`, `barcount`, `wap`, `hasgaps`, `ctime`) values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)' for row in ans.iterrows(): index, data = row values.append((data['symbol'], data['sdate'], data['open'], data['high'], data['low'], data['close'], data['volume'], data['barcount'], data['wap'], data['hasgaps'], time.time())) #print 'Index: %s, symbol: %s, date: %s, close: %s' % (index, data['symbol'], data['sdate'], data['close']) cur.executemany(header, values) conn.commit() cur.close() conn.close() time.sleep(5)
def createContract(self, secType, symbol, exchange, expiry=None, currency=None ): """ Create new IB Contract :param secType: Contract sector type: STK, OPT, FUT, IND, FOP, CASH,BAG, NEWS :param expiry: The expiration date. Use the format YYYYMM. :param symbol: This is the symbol of the underlying asset. :param exchange: The order destination, such as Smart. """ ibcontract = IBcontract() ibcontract.secType = secType if expiry: ibcontract.expiry = expiry if currency: ibcontract.currency = currency ibcontract.symbol = symbol ibcontract.exchange = exchange return ibcontract
def place_plain_order(expiry, symbol, right, strike, orderType, quantity, lmtPrice, orderId): """ Place a sinlge option order orderType="LMT" """ if orderId <= 0: orderId = None client, log_order = init_func() log_order.info("placing order ") ibcontract = IBcontract() ibcontract.secType = get_contract_details(symbol)["secType"] ibcontract.expiry = expiry ibcontract.symbol = symbol ibcontract.exchange = get_contract_details(symbol)["exchange"] ibcontract.right = right ibcontract.strike = strike ibcontract.multiplier = get_contract_details(symbol)["multiplier"] ibcontract.currency = get_contract_details(symbol)["currency"] iborder = IBOrder() iborder.action = bs_resolve(quantity) iborder.lmtPrice = lmtPrice iborder.orderType = orderType iborder.totalQuantity = abs(quantity) iborder.tif = get_order_defaults()["tif"] iborder.transmit = get_order_defaults()["transmit"] order_structure = client.place_new_IB_order(ibcontract, iborder, orderid=orderId) df1 = pd.DataFrame() for idx, x in order_structure.items(): temp = pd.DataFrame.from_dict(x, orient='index').transpose() df1 = df1.append(temp) if not df1.empty: df1 = df1.set_index(['orderid'], drop=True) print(df1) end_func(client=client)
def getPortfolio(self): ''' Returns list of triplets of current (contract, position in number of shares/contracts, market value of position) ''' portfolioList = [] # setup call back variables self.callback.accountEnd = False #self.callback.portfolioContract = None #self.callback.portfolioPosition = None #self.callback.portfolioSecMarketValue = None self.tws.reqAccountUpdates(1, self.accountNumber) while (not self.callback.accountEnd): self.callback.portfolioContract = None self.callback.portfolioPosition = None self.callback.portfolioSecMarketValue = None max_wait = datetime.timedelta(seconds=60) + datetime.datetime.now() while (self.callback.portfolioPosition is None or self.callback.portfolioContract is None or self.callback.portfolioSecMarketValue is None): if datetime.datetime.now() > max_wait: break if self.callback.portfolioPosition is not None and self.callback.portfolioContract is not None and self.callback.portfolioSecMarketValue is not None: myContract = Contract() myContract.exchange = "SMART" myContract.currency = "USD" myContract.symbol = self.callback.portfolioContractSymbol myContract.conId = self.callback.portfolioContractConId myContract.secType = self.callback.portfolioContractSecType myContract.strike = self.callback.portfolioContractStrike myContract.expiry = self.callback.portfolioContractExpiry myContract.right = self.callback.portfolioContractRight myPosition = self.callback.portfolioPosition mySecMarketValue = self.callback.portfolioSecMarketValue portfolioList.append( (myContract, myPosition, mySecMarketValue)) self.tws.reqAccountUpdates(0, self.accountNumber) return portfolioList
def get_cash_contracts(): symList = dict() systemdata = pd.read_csv('./data/systems/system.csv') print systemdata.columns systemdata = systemdata.reset_index() for i in systemdata.index: #print 'Read: ',i system = systemdata.ix[i] #print system contract = Contract() symbol = system['ibsym'] if system['ibtype'] == 'CASH': symbol = system['ibsym'] + system['ibcur'] if system['ibtype'] != 'BITCOIN': contract.symbol = system['ibsym'] contract.secType = system['ibtype'] contract.exchange = system['ibexch'] contract.currency = system['ibcur'] if system['ibtype'] == 'FUT': contract.localSymbol = system['iblocalsym'] symList[symbol] = contract return symList.values()
def getPortfolio(self): ''' Returns list of triplets of current (contract, position in number of shares/contracts, market value of position) ''' portfolioList = [] # setup call back variables self.callback.accountEnd = False #self.callback.portfolioContract = None #self.callback.portfolioPosition = None #self.callback.portfolioSecMarketValue = None self.tws.reqAccountUpdates(1, self.accountNumber) while (not self.callback.accountEnd): self.callback.portfolioContract = None self.callback.portfolioPosition = None self.callback.portfolioSecMarketValue = None max_wait = datetime.timedelta(seconds=60) + datetime.datetime.now() while (self.callback.portfolioPosition is None or self.callback.portfolioContract is None or self.callback.portfolioSecMarketValue is None): if datetime.datetime.now() > max_wait: break if self.callback.portfolioPosition is not None and self.callback.portfolioContract is not None and self.callback.portfolioSecMarketValue is not None: myContract = Contract() myContract.exchange = "SMART" myContract.currency = "USD" myContract.symbol = self.callback.portfolioContractSymbol myContract.conId = self.callback.portfolioContractConId myContract.secType = self.callback.portfolioContractSecType myContract.strike = self.callback.portfolioContractStrike myContract.expiry = self.callback.portfolioContractExpiry myContract.right = self.callback.portfolioContractRight myPosition = self.callback.portfolioPosition mySecMarketValue = self.callback.portfolioSecMarketValue portfolioList.append((myContract, myPosition, mySecMarketValue)) self.tws.reqAccountUpdates(0, self.accountNumber) return portfolioList
if prompt.lower() != 'yes': sys.exit() # Instantiate our callback object callback = PlaceOrderExample() # Instantiate a socket object, allowing us to call TWS directly. Pass our # callback object so TWS can respond. tws = EPosixClientSocket(callback) # Connect to tws running on localhost tws.eConnect("", 7496, 42) # Simple contract for GOOG contract = Contract() contract.exchange = "SMART" contract.symbol = "DELL" contract.secType = "STK" contract.currency = "USD" if orderId is None: print 'Waiting for valid order id' sleep(1) while orderId is None: print 'Still waiting for valid order id...' sleep(1) # Order details order = Order() order.action = 'BUY' order.lmtPrice = 0
from sysIB.wrapper_v3 import IBWrapper, IBclient from swigibpy import Contract as IBcontract if __name__ == "__main__": """ This simple example returns streaming price data """ callback = IBWrapper() client = IBclient(callback) ibcontract = IBcontract() ibcontract.secType = "FUT" ibcontract.expiry = "201812" ibcontract.symbol = "GE" ibcontract.exchange = "GLOBEX" ans = client.get_IB_market_data(ibcontract) print "Bid size, Ask size; Bid price; Ask price" print ans
from sysIB.wrapper_v2 import IBWrapper, IBclient from swigibpy import Contract as IBcontract if __name__ == "__main__": """ This simple example returns historical data """ callback = IBWrapper() client = IBclient(callback) # ibcontract = IBcontract() # ibcontract.secType = "FUT" # ibcontract.expiry="201809" # ibcontract.symbol="GE" # ibcontract.exchange="GLOBEX" ibcontract = IBcontract() ibcontract.secType = "CASH" # ibcontract.expiry="201809" ibcontract.symbol = "USD" ibcontract.exchange = "IDEALPRO" ibcontract.currency = "JPY" ans = client.get_IB_historical_data(ibcontract) print(ans)
from sysIB.wrapper_v2 import IBWrapper, IBclient from swigibpy import Contract as IBcontract from matplotlib.pyplot import show if __name__ == "__main__": """ This simple example returns the time """ callback = IBWrapper() client = IBclient(callback) ibcontract = IBcontract() ibcontract.secType = "FUT" ibcontract.expiry = "201406" ibcontract.symbol = "Z" ibcontract.exchange = "LIFFE" ans = client.get_IB_historical_data(ibcontract) ans.close.plot() show()
Note: If you are running this on the 'edemo' account it will probably give you back garbage Though the mechanics should still work This is because you see the orders that everyone demoing the account is trading!!! """ callback = IBWrapper() client=IBclient(callback) ibcontract = IBcontract() ibcontract.secType = "FUT" ibcontract.expiry="201703" ibcontract.symbol="GBL" ibcontract.exchange="DTB" ## Get contract details cdetails=client.get_contract_details(ibcontract) ## In particular we want the expiry. You cannot just use cdetails['expiry'][:6] to map back to the yyyymm ## expiry since certain contracts expire the month before they should! print "Expiry is %s" % cdetails['expiry'] ## Place the order, asking IB to tell us what the next order id is ## Note limit price of zero orderid1=client.place_new_IB_order(ibcontract, 10, 0.0, "MKT", orderid=None) print "" print "Placed market order, orderid is %d" % orderid1
"%s, Volume: %d") % (date, open, high, low, close, volume) # Instantiate our callback object callback = HistoricalDataExample() # Instantiate a socket object, allowing us to call TWS directly. Pass our # callback object so TWS can respond. tws = EPosixClientSocket(callback) # Connect to tws running on localhost tws.eConnect("", 7496, 42) # Simple contract for DELL dell = Contract() dell.exchange = "SMART" dell.symbol = "DELL" dell.secType = "STK" dell.currency = "USD" today = datetime.today() print "Requesting historical data for %s" % dell.symbol # Request some historical data. tws.reqHistoricalData( 1, #tickerId, dell, #contract, today.strftime("%Y%m%d %H:%M:%S %Z"), #endDateTime, "1 W", #durationStr, "1 day", #barSizeSetting, "TRADES", #whatToShow,
def place_or_modif_spread_order(expiry, symbol, right, strike_l, strike_s, orderType, quantity, lmtPrice, orderId): """ Place new option spread order or modify existing order orderType="LMT" Put orderId <= 0 if new order """ """ Modification of an open order through the API can be achieved by the same client which placed the original order. In the case of orders placed manually in TWS, the order can be modified by the client with ID 0. To modify an order, simply call the IBApi.EClient.placeOrder function again with the same parameters used to place the original order, except for the changed parameter. This includes the IBApi.Order.OrderId, which must match the IBApi.Order.OrderId of the original. It is not generally recommended to try to change order parameters other than the order price and order size. To change other parameters, it might be preferable to cancel the original order and place a new order. """ # http://interactivebrokers.github.io/tws-api/modifying_orders.html#gsc.tab=0 if orderId <= 0: orderId = None client, log_order = init_func() log_order.info("placing order ") underl = { 1001: RequestOptionData(symbol, get_contract_details(symbol)["secType"], expiry, strike_l, right, get_contract_details(symbol)["multiplier"], get_contract_details(symbol)["exchange"], get_contract_details(symbol)["currency"], 1001), 1002: RequestOptionData(symbol, get_contract_details(symbol)["secType"], expiry, strike_s, right, get_contract_details(symbol)["multiplier"], get_contract_details(symbol)["exchange"], get_contract_details(symbol)["currency"], 1002) } action1 = {1001: "BUY", 1002: "SELL"} list_results = client.getOptionsChain(underl) legs = [] log_order.info("Number of requests [%d]" % (len(list_results))) for reqId, request in list_results.items(): log_order.info( "Requestid [%d]: Option[%s] Results [%d]" % (reqId, str(request.get_in_data()), len(request.optionsChain))) for opt1 in request.optionsChain: leg1 = sy.ComboLeg() leg1.conId = opt1['conId'] leg1.ratio = get_order_defaults()["ratio"] leg1.action = action1[reqId] leg1.exchange = opt1['exchange'] legs.append(leg1) #sy.Contract.comboLegs ibcontract = IBcontract() ibcontract.comboLegs = sy.ComboLegList(legs) ibcontract.symbol = symbol ibcontract.secType = "BAG" # BAG is the security type for COMBO order ibcontract.exchange = get_contract_details(symbol)["exchange"] ibcontract.currency = get_contract_details(symbol)["currency"] iborder = IBOrder() iborder.action = bs_resolve(quantity) iborder.lmtPrice = lmtPrice iborder.orderType = orderType iborder.totalQuantity = abs(quantity) iborder.tif = get_order_defaults()["tif"] iborder.transmit = get_order_defaults()["transmit"] order_structure = client.place_new_IB_order(ibcontract, iborder, orderid=orderId) df1 = pd.DataFrame() for idx, x in order_structure.items(): temp = pd.DataFrame.from_dict(x, orient='index').transpose() df1 = df1.append(temp) if not df1.empty: df1 = df1.set_index(['orderid'], drop=True) print(df1) end_func(client=client)
""" callback = IBWrapper() #client=IBclient(callback, "DU220055") client=IBclient(callback, "All") #client.req_account_summary(10000) ibcontract = IBcontract() #ibcontract.secType = "FUT" #ibcontract.expiry="201509" #ibcontract.symbol="GBL" #ibcontract.exchange="DTB" ibcontract.secType = 'STK' ibcontract.exchange = 'SMART' ibcontract.currency = 'USD' ibcontract.primaryExchange = 'SMART' ibcontract.symbol = "TRUE" ## Get contract details cdetails=client.get_contract_details(ibcontract) ## In particular we want the expiry. You cannot just use cdetails['expiry'][:6] to map back to the yyyymm ## expiry since certain contracts expire the month before they should! print "Expiry is %s" % cdetails['expiry'] ## Once you have the portfolio positions then you can use these expiries to map back (account_value, portfolio_data)=client.get_IB_account_data()
if args.v: logging.basicConfig(handlers=[logging.StreamHandler()], level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%j-%H:%M:%S') else: logging.basicConfig(handlers=[logging.StreamHandler()], level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%j-%H:%M:%S') logging.debug(args) if args.sym: contract.symbol = args.sym if args.exc: contract.exchange = args.exc if args.st: contract.secType = args.st if args.cur: contract.currency = args.cur if args.id: contract.conId = args.id if args.exp: contract.expiry = args.exp if args.pex: contract.primaryExchange = args.pex if args.str: contract.strike = args.str if args.rt: contract.right = args.rt if args.mult: contract.multiplier = args.mult barsize = args.p datatype = args.t rth_only = args.rth pacing = args.pacing num_requests = args.n zerobased = args.z
def list_spread_prices_before_trade(symbol, expiry, query): """ List option spread prices before trade """ query1 = query.split(",") client, log_order = init_func() underl = {} for idx, x in enumerate(query1): underl[idx] = RequestOptionData( symbol, get_contract_details(symbol)["secType"], expiry, float(x[1:]), x[:1], get_contract_details(symbol)["multiplier"], get_contract_details(symbol)["exchange"], get_contract_details(symbol)["currency"], idx, comboLegs=None) action1 = {0: "BUY", 1: "SELL"} list_results = client.getOptionsChain(underl) legs = [] log_order.info("Number of requests [%d]" % (len(list_results))) for reqId, request in list_results.items(): log_order.info( "Requestid [%d]: Option[%s] Results [%d]" % (reqId, str(request.get_in_data()), len(request.optionsChain))) for opt1 in request.optionsChain: leg1 = sy.ComboLeg() leg1.conId = opt1['conId'] leg1.ratio = get_order_defaults()["ratio"] leg1.action = action1[reqId] leg1.exchange = opt1['exchange'] legs.append(leg1) ibcontract = IBcontract() ibcontract.comboLegs = sy.ComboLegList(legs) ibcontract.symbol = symbol ibcontract.secType = "BAG" # BAG is the security type for COMBO order ibcontract.exchange = get_contract_details(symbol)["exchange"] ibcontract.currency = get_contract_details(symbol)["currency"] ctrt = {} ctrt[100] = RequestOptionData(symbol, get_contract_details(symbol)["secType"], expiry, float(x[1:]), x[:1], get_contract_details(symbol)["multiplier"], get_contract_details(symbol)["exchange"], get_contract_details(symbol)["currency"], 100, comboLegs=None, contract=ibcontract) ctrt_prc = client.getMktData(ctrt) log_order.info("[%s]" % (str(ctrt_prc))) df1 = pd.DataFrame() #for id, req1 in ctrt_prc.iteritems(): # subset_dic = {k: req1.get_in_data()[k] for k in ('secType','symbol','comboLegsDescrip')} # subset_dic2 = {k: req1.get_out_data()[id][k] for k in ('bidPrice', 'bidSize', 'askPrice', 'askSize') } # dict1 = subset_dic.copy() # dict1.update(subset_dic2) # temp=pd.DataFrame.from_dict(dict1, orient='index').transpose() # df1=df1.append(temp) row1 = 0 for reqId, request in ctrt_prc.items(): row1 += 1 dict1 = request.get_in_data().copy() if reqId in request.get_out_data(): dict1.update(request.get_out_data()[reqId]) for key in dict1.keys(): df1.loc[row1, key] = dict1[key] df1 = df1.set_index(['secType', 'symbol', 'comboLegsDescrip'], drop=True) columns = [ 'bidPrice', 'bidSize', 'askPrice', 'askSize', '', 'modelDelta', 'modelImpliedVol', 'lastUndPrice', 'modelGamma', 'closePrice' ] cols = [val for val in columns if val in df1.columns] print(df1[cols]) end_func(client=client)
con_group.add_argument("-pex", help="primary exchange of the contract") con_group.add_argument("-str", help="strike price of the option contract") con_group.add_argument("-rt", choices=["C", "P"], help="right of the option contract (C/P)") con_group.add_argument("-mult", help="multiplier of the contract") args = parser.parse_args() if args.v: logging.basicConfig(handlers=[logging.StreamHandler()], level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%j-%H:%M:%S') else: logging.basicConfig(handlers=[logging.StreamHandler()], level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%j-%H:%M:%S') logging.debug(args) if args.sym: contract.symbol = args.sym if args.exc: contract.exchange = args.exc if args.st: contract.secType = args.st if args.cur: contract.currency = args.cur if args.id: contract.conId = args.id if args.exp: contract.expiry = args.exp if args.pex: contract.primaryExchange = args.pex if args.str: contract.strike = args.str if args.rt: contract.right = args.rt if args.mult: contract.multiplier = args.mult barsize = args.p datatype = args.t rth_only = args.rth pacing = args.pacing num_requests = args.n zerobased = args.z
from sysIB.wrapper_v2 import IBWrapper, IBclient from swigibpy import Contract as IBcontract if __name__ == "__main__": """ This simple example returns historical data """ callback = IBWrapper() client = IBclient(callback) ibcontract = IBcontract() ibcontract.secType = "STK" ibcontract.expiry = "201809" ibcontract.symbol = "GE" ibcontract.exchange = "GLOBEX" ans = client.get_IB_historical_data(ibcontract) print(ans)
from sysIB.wrapper_v2 import IBWrapper, IBclient from swigibpy import Contract as IBcontract from matplotlib.pyplot import show if __name__=="__main__": """ This simple example returns the time """ callback = IBWrapper() client=IBclient(callback) ibcontract = IBcontract() ibcontract.secType = "FUT" ibcontract.expiry="201406" ibcontract.symbol="Z" ibcontract.exchange="LIFFE" ans=client.get_IB_historical_data(ibcontract) ans.close.plot() show()
Note: If you are running this on the 'edemo' account it will probably give you back garbage Though the mechanics should still work This is because you see the orders that everyone demoing the account is trading!!! """ callback = IBWrapper() client = IBclient(callback) ibcontract = IBcontract() ibcontract.secType = "FUT" ibcontract.expiry = "201406" ibcontract.symbol = "GBL" ibcontract.exchange = "DTB" ## Get contract details cdetails = client.get_contract_details(ibcontract) ## In particular we want the expiry. You cannot just use cdetails['expiry'][:6] to map back to the yyyymm ## expiry since certain contracts expire the month before they should! print "Expiry is %s" % cdetails['expiry'] ## Once you have the portfolio positions then you can use these expiries to map back positions = client.get_IB_positions() accountinfo = client.get_IB_account_data()
"%s, Volume: %d" ) % (date, open, high, low, close, volume) # Instantiate our callback object callback = HistoricalDataExample() # Instantiate a socket object, allowing us to call TWS directly. Pass our # callback object so TWS can respond. tws = EPosixClientSocket(callback) # Connect to tws running on localhost tws.eConnect("", 7496, 42) # Simple contract for DELL dell = Contract() dell.exchange = "SMART" dell.symbol = "DELL" dell.secType = "STK" dell.currency = "USD" today = datetime.today() print "Requesting historical data for %s" % dell.symbol # Request some historical data. tws.reqHistoricalData( 1, #tickerId, dell, #contract, today.strftime("%Y%m%d %H:%M:%S %Z"), #endDateTime, "1 W", #durationStr, "1 day", #barSizeSetting, "TRADES", #whatToShow,
def enterPositions(self, weights, execution_sleep=True): print "----------------------MAKING TRADES ON IB---------------------------" # Instantiate our callback object callback = self.PlaceOrderExample() # Instantiate a socket object, allowing us to call TWS directly. Pass our # callback object so TWS can respond. tws = EPosixClientSocket(callback) # Connect to tws running on localhost tws.eConnect("", 7496, 42) # account updates tws.reqAccountUpdates(True, self.accountNumber) sleep(1) print "available funds: %s" % (self.availableFunds) print "net liquidation value: %s" % (self.netLiquidationValue) ###DELAY UNTIL MARKET HOURS if execution_sleep: day_of_week = datetime.now().isoweekday() # if weekday, and we scanned after midnight, set execution time to this morning at 10:30 am time_now = datetime.now() if ( day_of_week in range(1, 6) and (time_now.hour >= 0 and time_now.hour < 10) and (time_now.minute >= 0 and time_now.minute < 30) ): execution_time = datetime( year=time_now.year, month=time_now.month, day=time_now.day, hour=10, minute=30 ) # otherwise, set to next trading day, morning at 10:30am else: execution_time = datetime.now() execution_time = execution_time + dt.timedelta(days=1) while execution_time.isoweekday() > 5: execution_time = execution_time + dt.timedelta(days=1) execution_time = datetime( year=execution_time.year, month=execution_time.month, day=execution_time.day, hour=10, minute=30 ) to_sleep = (execution_time - datetime.now()).total_seconds() print "----------sleeping until execution time of %s---------------" % (execution_time) # sleep until that time sleep(to_sleep) for stock in weights: print ("\n=====================================================================") print (" Trading " + stock) print ("=====================================================================\n") stock_price = Trader.get_quote([stock])[0][self.QUOTE_LAST] print "%s last stock price: %s" % (stock, stock_price) contract = Contract() contract.symbol = stock contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" if self.orderId is None: print ("Waiting for valid order id") sleep(1) while self.orderId is None: print ("Still waiting for valid order id...") sleep(1) # Order details order = Order() order.action = "BUY" # order.lmtPrice = 140 order.orderType = "MKT" dollar_value = self.availableFunds * weights[stock] order.totalQuantity = int(round(dollar_value / stock_price, 0)) # order.algoStrategy = "AD" order.tif = "DAY" # order.algoParams = algoParams order.transmit = True print ( "Placing order for %d %s's, dollar value $%s (id: %d)" % (order.totalQuantity, contract.symbol, dollar_value, self.orderId) ) # Place the order tws.placeOrder(self.orderId, contract, order) # orderId, # contract, # order print ("\n=====================================================================") print (" Order placed, waiting for TWS responses") print ("=====================================================================\n") sleep(3) # reset orderid for next self.orderId = self.orderId + 1 print ("\n=====================================================================") print (" Trade done.") print ("=====================================================================\n") print ("******************* Press ENTER to quit when done *******************\n") input() print ("\nDisconnecting...") tws.eDisconnect()
print("validExchanges: %s" % contractDetails.validExchanges) # Instantiate our callback object callback = ContractDetailsExample() # Instantiate a socket object, allowing us to call TWS directly. Pass our # callback object so TWS can respond. tws = EPosixClientSocket(callback) # Connect to tws running on localhost tws.eConnect("", 7496, 42) # Simple contract for GOOG contract = Contract() contract.exchange = "SMART" contract.symbol = "GOOG" contract.secType = "STK" contract.currency = "USD" today = datetime.today() print("Requesting contract details...") # Perform the request tws.reqContractDetails( 42, # reqId, contract, # contract, ) print("\n=====================================================================") print(" Contract details requested, waiting for TWS responses")