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 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, ticker, secType): contract = Contract() contract.exchange = "SMART" # Default exchange, IB routing algo contract.symbol = ticker contract.secType = secType 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 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 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 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 create_contract(self): # Simple contract for GOOG contract = Contract() contract.exchange = "SMART" contract.symbol = "GOOG" contract.secType = "STK" contract.currency = "USD" return contract
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 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 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 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()
from sysIB.wrapper_v5 import IBWrapper, IBclient from swigibpy import Contract as IBcontract import time from pprint import pprint if __name__ == "__main__": """ Example of getting contract and account details """ callback = IBWrapper() client = IBclient(callback) ibcontract = IBcontract() ibcontract.secType = "FUT" 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! pprint(cdetails) # will look something like: [{ 'contractMonth': '201612', 'currency': 'EUR',
This simple example places an order, checks to see if it is active, and receives fill(s) 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, "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
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()
second_end = tz.localize(second_end) return first_start, first_end, second_start, second_end api_started = threading.Event() contract_details_received = threading.Event() historical_data_received = threading.Event() num_batches_received = 0 num_requests = None workstation_exited = False tws = None clientid = None contract = Contract() output_file = None prev_rth_start = None prev_rth_end = None next_rth_start = None next_rth_end = None prev_session_start = None prev_session_end = None next_session_start = None next_session_end = None contract_tz = None last_time = None prev_last_time = None period = None
from swigibpy import Contract as IBcontract from sysIB.wrapper_v5 import IBWrapper, IBclient if __name__ == "__main__": """ This simple example places an order, checks to see if it is active, and receives fill(s) 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 = "201509" ibcontract.symbol = "GBL" # Commented to avoid this error "Why do I receive an error 200 - No security definition has been found for the request when I call reqContractDetails, reqMktData, or addOrder() for a stock contract?" 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 (account_value, portfolio_data) = client.get_IB_account_data()
import time from swigibpy import Contract as IBcontract from sysIB.order_creation_wrapper import IBWrapper, IBclient if __name__ == "__main__": """ This simple example places an order, checks to see if it is active, and receives fill(s) 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 = "STK" ibcontract.expiry = "201603" ibcontract.symbol = "GOOG" ibcontract.exchange = "SMART" ## 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']) print(client.get_managed_accounts()) ## 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, "DU271807", 10, 0.0, "MKT", orderid=None) print("")
print("History %s - Open: %s, High: %s, Low: %s, Close: " + "%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,
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="201612" 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 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()
def winError(self, msg, lastError): print("TWS reports API error: %s" % msg) # Instantiate our callback object callback = CustomErrorExample() # 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 (badly formed) contract contract = Contract() contract.exchange = "SMART" contract.secType = "STK" today = datetime.today() print("Sending bad request for historical data") # Request some historical data. tws.reqHistoricalData( 2, # tickerId, contract, # contract, today.strftime("%Y%m%d %H:%M:%S %Z"), # endDateTime, "1 W", # durationStr, "1 day", # barSizeSetting, "TRADES", # whatToShow, 0, # useRTH,
if __name__ == "__main__": """ This simple example places an order, checks to see if it is active, and receives fill(s) 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
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
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
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)
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)
from sysIB.wrapper_v5 import IBWrapper, IBclient from swigibpy import Contract as IBcontract import time from pprint import pprint if __name__ == "__main__": """ Example of getting contract and account details """ callback = IBWrapper() client = IBclient(callback) ibcontract = IBcontract() ibcontract.secType = "FUT" 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! pprint(cdetails) # will look something like: [{'contractMonth': '201612', 'currency': 'EUR',
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)
if __name__=="__main__": """ This simple example places an order, checks to see if it is active, and receives fill(s) 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
from 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(IBWrapper()) ibcontract = IBcontract() ibcontract.secType = "FUT" ibcontract.expiry = "201612" ibcontract.symbol = "ES" ibcontract.exchange = "GLOBEX" ibcontract.currency = "USD" ans = client.get_IB_market_data(ibcontract, seconds=1) print "Bid size, Ask size; Bid price; Ask price" print ans
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 = "STK" #ibcontract.expiry = "201612" ibcontract.symbol = "GOOG" ibcontract.exchange = "SMART" ans = client.get_IB_market_data(ibcontract) print("Bid size, Ask size; Bid price; Ask price") print(ans)
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()
"account, are you sure? (Type yes to continue): ") 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'
return first_start, first_end, second_start, second_end api_started = threading.Event() contract_details_received = threading.Event() historical_data_received = threading.Event() num_batches_received = 0 num_requests = None workstation_exited = False tws = None clientid = None contract = Contract() output_file = None prev_rth_start = None prev_rth_end = None next_rth_start = None next_rth_end = None prev_session_start = None prev_session_end = None next_session_start = None next_session_end = None contract_tz = None last_time = None prev_last_time = None period = None
print ( "History %s - Open: %s, High: %s, Low: %s, Close: " + "%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,
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)
print("ratings: %s" % contractDetails.ratings) 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=====================================================================")