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 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, 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 create_contract(self): # Simple contract for GOOG contract = Contract() contract.exchange = "SMART" contract.symbol = "GOOG" contract.secType = "STK" contract.currency = "USD" return contract
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 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()
"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'
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,