def hist(): #print to console print("%s" %ticker ) print("%s" %type) print("%s" %exc) print ("%s" %cur) print("%s" %enddate1) print("%s" %expiry) print("%s" %fetch) print("%s" %ds) #functionality #retrieve functions from other files create = contract() callback.initiate_variables() #fetch from TWS contract_Details1 = create.create_contract(ticker,type,exc,cur,'','',expiry,mul)#,'','',exp4,multi) #"", "", #"20170317", #"50") # ('NG', 'FUT', 'NYMEX', 'USD') data_endtime = datetime.now().strftime("%Y%m%d %H:%M:%S") tws.reqHistoricalData(9000, contract_Details1,enddate1 , fetch, ds, "TRADES", 0, 1) time.sleep(1) data = pd.DataFrame(callback.historical_Data, columns=["reqId", "date", "open", "high", "low", "close", "volume", "count", "WAP", "hasGaps"]) #data['DateTime'] = data['date'].apply(lambda x: pd.to_datetime(str(x), format='%Y%m%d')) #data = data.drop('date', 1) #global dat #dat=data.drop(data.index[len(data) - 1]) #print("%s" %data) df=data df[['DateTime']] = df[['date']].applymap(str).applymap(lambda s: "{}/{}/{} {}".format(s[0:4], s[4:6], s[6:8], s[8:])) data=df[["DateTime","close"]] print("%s" % data) base_dir = dir filename = fname + '.csv' data.to_csv(os.path.join(base_dir, filename)) return render_template('trades.html', ticker=ticker, type=type, exc=exc, enddate1=enddate1, cur=cur, expiry=expiry, mul=mul, ds=ds)
def make_contract(self): #Initialised contract object from IB library. create = contract() #Create contract info. contract_info = create.create_contract(symbol=self._underlying, secType=self._sec_type, exchange=self._exchange, currency=self._currency) return contract_info
def option(self, opt_type, opt_strike, month_expiry, year_expiry): ''' Argument: opt_type: This is a string either a 'Call' or 'Put' opt_strike: the option strike month_expiry: an integer for the expiry month year_expiry: an integer for the expiry year ''' #Initiate variables. self.opt_type = opt_type self.opt_strike = opt_strike self.month_expiry = month_expiry self.year_expiry = year_expiry #Create contract object create = contract() #=================================================== #*************************************************** #Create the expiry. #Convert the month with leading zero. if (self.month_expiry <= 9): self.month_expiry = "%02d" % (self.month_expiry) #convert the year to expiry to string. self.year_expiry = str(self.year_expiry) #Create the expiry. expiry = self.year_expiry + self.month_expiry #*************************************************** #=================================================== #Create the data for VIX option. #If the expiry is provided, then the VIX code name is not required. symbol = 'VIX' sec_type = 'OPT' exchange = 'SMART' currency = 'USD' right = self.opt_type strike = self.opt_strike contract_info = create.create_contract(symbol = 'VIX', secType = 'OPT', exchange = 'SMART', currency = 'USD', right = self.opt_type, strike = str(self.opt_strike), expiry = expiry, multiplier = 100, tradingClass = 'VIX') return contract_info
def __init__(self, account_name: str, host: str, port: int, client_id: int): self.account_name = account_name # Instantiate IBWrapper callback. self.callback = IBWrapper() # Instantiate EClientSocket and return data to callback self.tws = EClientSocket(self.callback) # Connect to TWS. self.tws.eConnect(host, port, client_id) # Instantiate contract class. self.create = contract() self.callback.initiate_variables()
def __init__(self, datadecoder): self.accountName = "asd781820" self.callback = IBWrapper() self.tws = EClientSocket(self.callback) self.host = "" self.port = 4002 self.clientId = 8 self.tws.eConnect(self.host, self.port, self.clientId) self.dd = datadecoder self.create = contract() self.callback.initiate_variables() self.callback.initiate_variables() self.tws.reqAccountSummary(8, 'All', 'TotalCashValue') self.filedf = datadecoder.usabledf self.datadecoder = datadecoder contract_Details = self.create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD') tickerId = 10000 self.tws.reqRealTimeBars(tickerId, contract_Details, 5, "MIDPOINT", 0) self.tickerId = 9010 self.df = pd.read_csv('df.csv') self.RbinDict = bqe.makeRDf(self.df) self.column_index_value_dict, self.binDict = bqe.makeDf(self.df)
def futures(self, month_expiry, year_expiry): #Initiate arguments. self.month_expiry = month_expiry self.year_expiry = year_expiry #Create contract object create = contract() #=================================================== #*************************************************** #Create the expiry. #Convert the month with leading zero. if (self.month_expiry <= 9): self.month_expiry = "%02d" % (self.month_expiry) #convert the year to expiry to string. self.year_expiry = str(self.year_expiry) #Create the expiry. expiry = self.year_expiry + self.month_expiry #*************************************************** #=================================================== #Create contract info. #If the expiry is provided, then the VIX code name is not required. contract_info = create.create_contract(symbol = 'VIX', secType = 'FUT', exchange = 'CFE', currency = 'USD', right = None, strike = None, expiry = expiry, multiplier = None, tradingClass = 'VX') return contract_info
wdw = 25 ctime = 0 r_sflag = 0 r_qty = 0 cnt = 0 global o_type ,order_id # end of intializations callback = IBWrapper() tws = EClientSocket(callback) host = "" port = 7497 clientId = 100 create = contract() callback.initiate_variables() tws.eConnect(host, port, clientId) print("connected") ####dummy data request contract_Details1 = create.create_contract("ES" ,"FUT" ,"GLOBEX" ,"USD" ,'' ,'' ,'20170616' ,'50') tickerId = random.randint(1, 1000000) # print(datetime.now()) tws.reqRealTimeBars(tickerId, contract_Details1, 5, "TRADES", 0) ddata = list(callback.real_timeBar) ddata = pd.DataFrame(callback.real_timeBar, columns=["reqId", "time", "open", "high", "low", "close", "volume", "wap",
from datetime import datetime from IBWrapper import IBWrapper, contract from ib.ext.EClientSocket import EClientSocket from ib.ext.ScannerSubscription import ScannerSubscription from __future__ import print_function if __name__ == "__main__": callback = IBWrapper() # Instantiate IBWrapper tws = EClientSocket(callback) # Instantiate EClientSocket host = "" port = 7496 clientId = 5000 tws.eConnect(host, port, clientId) # Connect to TWS tws.setServerLogLevel(5) accountName = "DU123456" # Change to your own account create = contract() # Instantiate contract class # Initiate attributes to receive data. At some point we need a separate class for this callback.initiate_variables() # Account and Portfolio ############################################################## # reqAccountUpdates ---> updateAccountTime self.update_AccountTime # updateAccountValue self.update_AccountValue # updatePortfolio self.update_Portfolio # accountDownloadEnd self.accountDownloadEnd_flag # reqAccountSummary ---> accountSummary self.account_Summary # cancelAccountSummary # accountSummaryEnd self.account_SummaryEnd_flag # reqPositions ---> position self.update_Position # cancelPositions # positionEnd self.positionEnd_flag
def getdata(): # ticker global tick global mySymbol global optionmenus mySymbol = tick.get() # type global box_value global type type = box_value.get() #EXCHANGE global box_value2 global exch1 exch1 = box_value2.get() # currency global box_value3 global cur cur = box_value3.get() #enddate global box_value11 global yr1 yr1 = box_value11.get() global box_value12 global yr2 yr2 = box_value12.get() global box_value13 global yr3 yr3 = box_value13.get() global yr4 yr4 = yr1 + yr2 + yr3 + " " global yr5 yr5 = "12:00:00" + " " + "IST" global yr6 yr6 = yr4 + yr5 #expiry global box_value14 global exp1 exp1 = box_value14.get() global box_value15 global exp2 exp2 = box_value15.get() global box_value16 global exp3 exp3 = box_value16.get() global exp4 exp4 = exp1 + exp2 + exp3 #multiplier global multp global multi multi = multp.get() #fetch data for global bar1 global bar2 bar2 = bar1.get() global box_value4 global bar3 bar3 = box_value4.get() global bardat bardat = bar2 + " " + bar3 #barsize global box_value5 global bar4 bar4 = box_value5.get() #directory global box_value6 global ent global pat pat = box_value6.get() global pat2 pat2 = ent.get() global pat3 pat3 = pat + pat2 create = contract() callback.initiate_variables() # calling historical_Data attribute from intiate_variable function under IBWrapper class print("Testing Historical Data\n") contract_Details1 = create.create_contract(mySymbol, type, exch1, cur, '', '', exp4, multi) #"", "", #"20170317", #"50") # ('NG', 'FUT', 'NYMEX', 'USD') data_endtime = datetime.now().strftime("%Y%m%d %H:%M:%S") tws.reqHistoricalData(9000, contract_Details1, yr6, bardat, bar4, "TRADES", 0, 1) time.sleep(1) data = pd.DataFrame(callback.historical_Data, columns=[ "reqId", "date", "open", "high", "low", "close", "volume", "count", "WAP", "hasGaps" ]) dat = data.drop(data.index[len(data) - 1]) base_dir = pat3 global fname global ffname ffname = fname.get() filename = ffname + '.csv' #filename = mySymbol + '.csv' dat.to_csv(os.path.join(base_dir, filename))
- accountName cannot be changed (is set for papar252) - port and clientId are arbitrary but must match values in TWS/IB Gateway config file ''' accountName = "DU603835" callback = IBWrapper() tws = EClientSocket(callback) host = "" port = 7497 clientId = 100 ################################################################################ tws.eConnect(host, port, clientId) #outputs server information to commandline #tws.setServerLogLevel(5) contract = contract() callback.initiate_variables() ################################################################################ ''' https://www.interactivebrokers.com/en/software/api/api.htm Requesting Account Changes: - I believe this allows you to subcribe to changes to your account after orders - this could also be implemented by an explicit call to Account Summary ''' tws.reqAccountUpdates(1, accountName) time.sleep(2) df_account_updates = pd.DataFrame(callback.update_AccountValue, columns = ['key', 'value', 'currency', 'accountName']) print('df_account_updates:\n',df_account_updates,'\n\n')
from datetime import datetime from IBWrapper import IBWrapper, contract from ib.ext.EClientSocket import EClientSocket from ib.ext.ScannerSubscription import ScannerSubscription if __name__=="__main__": callback = IBWrapper() # Instantiate IBWrapper tws = EClientSocket(callback) # Instantiate EClientSocket host = "" port = 7496 clientId = 5000 tws.eConnect(host, port, clientId) # Connect to TWS tws.setServerLogLevel(5) accountName = "DU123456" # Change to your own account create = contract() # Instantiate contract class # Initiate attributes to receive data. At some point we need a separate class for this callback.initiate_variables() # Account and Portfolio ############################################################## # reqAccountUpdates ---> updateAccountTime self.update_AccountTime # updateAccountValue self.update_AccountValue # updatePortfolio self.update_Portfolio # accountDownloadEnd self.accountDownloadEnd_flag # reqAccountSummary ---> accountSummary self.account_Summary # cancelAccountSummary # accountSummaryEnd self.account_SummaryEnd_flag # reqPositions ---> position self.update_Position # cancelPositions # positionEnd self.positionEnd_flag