def test(): # Connect to the Trader Workstation (TWS) running on the # usual port of 7496, with a clientId of 100 # (The clientId is chosen by us and we will need # separate IDs for both the execution connection and # market data connection) tws_conn = Connection.create(port=7496, clientId=100) tws_conn.connect() # Assign the error handling function defined above # to the TWS connection tws_conn.register(error_handler, 'Error') # Assign all of the server reply messages to the # reply_handler function defined above tws_conn.registerAll(reply_handler) # Create an order ID which is 'global' for this session. This # will need incrementing once new orders are submitted. order_id = 1 # Create a contract in GOOG stock via SMART order routing goog_contract = create_contract('GOOG', 'STK', 'SMART', 'SMART', 'USD') # Go long 100 shares of Google goog_order = create_order('MKT', 1000, 'BUY') # Use the connection to the send the order to IB tws_conn.placeOrder(order_id, goog_contract, goog_order) # Disconnect from TWS tws_conn.disconnect()
def __init__(self, host='localhost', port=4001, client_id=130, is_use_gateway=False, evaluation_time_secs=20, resample_interval_secs='30s', moving_window_period=dt.timedelta(seconds=60)): self.moving_window_period = moving_window_period # self.chart = Chart() self.ib_util = IBUtil() # Store parameters for this model # self.strategy_params = StrategyParameters(evaluation_time_secs, # resample_interval_secs) self.stocks_data = {} # Dictionary storing StockData objects. self.symbols = None # List of current symbols self.account_code = "" self.prices = None # Store last prices in a DataFrame self.ohlc = None # I need another store for minute data (I think) self.trade_qty = 0 self.order_id = 0 self.lock = threading.Lock() #addition for hdf store self.data_path = os.path.normpath("/Users/maxime_back/Documents/avocado/data.csv") self.ohlc_path = os.path.normpath("/Users/maxime_back/Documents/avocado/ohlc.csv") self.last_trim = dt.datetime.now() # Use ibConnection() for TWS, or create connection for API Gateway self.conn = ibConnection() if is_use_gateway else \ Connection.create(host=host, port=port, clientId=client_id) self.__register_data_handlers(self.__on_tick_event, self.__event_handler)
def __init__(self, host='localhost', port=4001, client_id=101, is_use_gateway=False, evaluation_time_secs=20, resample_interval_secs='30s', moving_window_period=dt.timedelta(hours=1)): self.moving_window_period = moving_window_period self.chart = Chart() self.ib_util = IBUtil() # Store parameters for this model self.strategy_params = StrategyParameters(evaluation_time_secs, resample_interval_secs) self.stocks_data = {} # Dictionary storing StockData objects. self.symbols = None # List of current symbols self.account_code = "" self.prices = None # Store last prices in a DataFrame self.trade_qty = 0 self.order_id = 0 self.lock = threading.Lock() # Use ibConnection() for TWS, or create connection for API Gateway self.conn = ibConnection() if is_use_gateway else \ Connection.create(host=host, port=port, clientId=client_id) self.__register_data_handlers(self.__on_tick_event, self.__event_handler)
def __init__(self): tws = Connection.create(port=7496, clientId=101) tws.connect() tws.registerAll(self.reply_handler) tws.register(self.error_handler, message.Error) tws.register(self.my_hist_data_handler, message.historicalData) self.tws=tws self.histdata = list()
def connect(self): self.update_connection_status("Connecting") api_hostname = environ["TXTRADER_API_HOST"] api_port = int(environ["TXTRADER_API_PORT"]) api_client_id = int(environ["TXTRADER_API_CLIENT_ID"]) self.output("Connnecting to TWS API at %s:%d with client id %d" % (api_hostname, api_port, api_client_id)) self.tws_conn = Connection.create(host=api_hostname, port=api_port, clientId=api_client_id) self.tws_conn.registerAll(self.reply_handler) self.tws_conn.connect()
def main(): conn = Connection.create(port=7497, clientId=999) conn.connect() oid = 1 cont = make_contract('SPY', 'STK', 'SMART', 'SMART', 'USD') offer = make_order('BUY', 1, 200) conn.placeOrder(oid, cont, offer) conn.disconnect()
def __init__(self, clientId=999): self.tws_conn = Connection.create(port=7496, clientId=clientId) self.tws_conn.connect() self.tws_conn.register(error_handler, 'Error') self.tws_conn.registerAll(reply_handler) self.ib_orderid_fname="ib_orderid_fname.p" if os.path.isfile(self.ib_orderid_fname): self.order_id = pickle.load(open(self.ib_orderid_fname, 'rb')) else: self.order_id = 1
def main(): conn = Connection.create(port=7496, clientId=994) conn.registerAll(print_message_from_ib) conn.connect() #In future blog posts, this is where we'll write code that actually does #something useful, like place orders, get real-time prices, etc. import time time.sleep(1) #Simply to give the program time to print messages sent from IB conn.disconnect()
def test_make_order(): conn = Connection.create(port=7496, clientId=99) conn.connect() conn.register(error_handler, 'Error') conn.registerAll(reply_handler) print 'connect' oid = 7; contract = make_contract('TSLA', 'STK', 'SMART', 'SMART', 'USD') offer = make_order('BUY', 100, 200) print contract print offer conn.placeOrder(oid, contract, offer)
def main(): global conn print "HFT model started." # Use ibConnection() for TWS, or create connection for API Gateway #conn = ibConnection() conn = Connection.create(port=4001, clientId=101) register_data_handlers() conn.connect() # Input your stocks of interest stocks = ("C", "MS") setup_stocks_data(stocks) request_streaming_data(conn) print "Boot strapping..." start_time = time.time() boot_strap_long_term(conn) wait_for_boot_strap_lt_to_complete() boot_strap_short_term(conn) wait_for_boot_strap_st_to_complete() print_elapsed_time(start_time) strategy_params.set_bootstrap_completed() print "Calculating strategy parameters..." start_time = time.time() calculate_params(stocks_data) print_elapsed_time(start_time) print "Bridging historical data..." start_time = time.time() bridge_historical_and_present_ticks(stocks_data, ticks_data, datetime.now()) print_elapsed_time(start_time) print "Trading started." try: plot_stocks(strategy_params) while True: update_charts() time.sleep(1) except Exception, e: print "Cancelling...", cancel_market_data_request() print "Disconnecting..." conn.disconnect() time.sleep(1) print "Disconnected."
def main(): conn = Connection.create(port=7497, clientId=88) #Has to be connected to Global settings of TWS conn.connect() oid = main.count #Order number print (oid) cont = make_contract('anf', 'STK', 'SMART', 'SMART', 'USD') #Check exch name for stock symbol offer = make_order('BUY',100,16.30) conn.placeOrder(oid, cont, offer) print(oid, str(cont), offer) conn.disconnect()
def main(): # port.main() # prices.main() # connects to TWS-- make sure to include your port and clientID here conn = Connection.create(port='{YOUR PORT}', clientId='{YOUR CLIENT_ID}') values = contrarian_plays(to_integer(datetime.date.today())) send_orders(values[0], values[1], conn) # for some reason if there is no break between transactions it won't work time.sleep(5) portfolio = values[2] # checks if there are any stocks to be sold check_sells(conn, portfolio) conn.disconnect()
def get_data_ib(self, id, endDateTime, durationStr, barSizeSetting, whatToShow, useRTH, formatDate): con = Connection.create(port=7496, clientId=1) con.connect() con.register(self.watcher, message.historicalData) # time.sleep(1) #con.reqMktData(id, self.contract, '', False) con.reqHistoricalData(id, self.contract, endDateTime, durationStr, barSizeSetting, whatToShow, useRTH, formatDate) time.sleep(1) con.cancelHistoricalData(id) time.sleep(1) con.disconnect() return self.data
def __init__(self, host='localhost', port=4001, client_id=101, is_use_gateway=False, evaluation_time_secs=20, resample_interval_secs='30s', moving_window_period=dt.timedelta(hours=1)): self.moving_window_period = moving_window_period self.chart = Chart() self.ib_util = IBUtil() self.strategy_params = StrategyParameters(evaluation_time_secs, resample_interval_secs) self.stocks_data = {} self.symbols = None self.account_code = "" self.prices = None self.trade_qty = 0 self.order_id = 0 self.lock = threading.Lock() self.conn = ibConnection() if is_use_gateway else \ Connection.create(host=host, port=port, clientId=client_id) self.__register_data_handlers(self.__on_tick_event, self.__event_handler)
def get_connection(client_id=1): conn = Connection.create(host='localhost', port=7496, clientId=client_id) conn.register(error_handler, 'Error') conn.connect() time.sleep(1) return conn
sym, tdate, msg.open, msg.high, msg.low, msg.close, msg.volume) newDataList = newDataList + [dataStr] else: print 'next list' rpu_rp.WriteStringsToFile(fname, '') #flush the file for a in newDataList: if len(a) > 2: rpu_rp.WriteStringsToFileAppend(fname, a) newDataList = [] ########## newDataList = [] print 'connecting hdownload flex' uniqueclientId = '125' tws_conn = Connection.create(port=7496, clientId=uniqueclientId) #need separate IDs for both the execution connection and tws_conn = Connection.create(port=7496, clientId=125) tws_conn.connect() tws_conn.register(Mod_ibutiles.error_handler, 'Error') tws_conn.registerAll(reply_handler) tws_conn.register(historical_data_handler, message.historicalData) ####################################### def dload(symlist, barlist, strikelist, expirylist): print symlist, barlist global bar, sym trans_id = 0 strikelist = [1] expirylist = [1]
def connect_to_tws(self): self.tws_conn = Connection.create(port=self.port, clientId=self.client_id) self.tws_conn.connect()
order = Order() order.m_orderType = order_type order.m_totalQuantity = quantity order.m_action = action order.m_account = account return order # ib_api_demo.py if __name__ == "__main__": # Connect to the Trader Workstation (TWS) running on the # usual port of 7497, with a clientId of 000 # (The clientId is chosen by us and we will need # separate IDs for both the execution connection and # market data connection) tws_conn = Connection.create(port=7497, clientId=000) tws_conn.connect() # Assign the error handling function defined above # to the TWS connection tws_conn.register(error_handler, 'Error') # Assign all of the server reply messages to the # reply_handler function defined above tws_conn.registerAll(reply_handler) # Create an order ID which is 'global' for this session. This # will need incrementing once new orders are submitted. order_id = 503 # has to change each time # Create a contract in GOOG stock via SMART order routing
query = ("UPDATE " + Table + " SET ninetyvol = " + str(ninetyd) + " where ID =\'" + str(ID1[0]) + "\';") logger.debug('Query is %s', query) print(query) cur.execute(query) cnx.commit() Flag = 1 logger.debug('Flag set to %s', Flag) print(Flag) return (Flag) while Flag == 0: logger.debug('Flag set to %s', Flag) conn = Connection.create(port=4002, clientId=999) conn.connect() logger.debug('Connecting to Server') time.sleep(1) conn.register( reply_handler, 'HistoricalData' ) #By registering "HistoricalData" --the Method name only --we can eliminate all the open order garbage logger.debug('Registered HistoricalData Reply Handler') time.sleep(1) qqq = Contract() qqq.m_symbol = Table qqq.m_secType = 'STK' qqq.m_exchange = 'SMART:ISLAND' qqq.m_currency = 'USD' logger.debug('Requesting historical data') conn.reqHistoricalData(1, qqq, '', '1 D', '1 day', 'TRADES', 0, 1)
def makeStkContract(contractTuple): newContract = Contract() newContract.m_symbol = contractTuple[0] newContract.m_secType = contractTuple[1] newContract.m_exchange = contractTuple[2] newContract.m_currency = contractTuple[3] newContract.m_expiry = contractTuple[4] newContract.m_strike = contractTuple[5] newContract.m_right = contractTuple[6] print('Contract Values:%s,%s,%s,%s,%s,%s,%s:' % contractTuple) return newContract if __name__ == '__main__': con = Connection.create(port=7496, clientId=100) con = ibConnection() con.registerAll(watcher) showBidAskOnly = True # set False to see the raw messages if showBidAskOnly: con.unregister(watcher, message.tickSize, message.tickPrice, message.tickString, message.tickOptionComputation) con.register(my_BidAsk, message.tickPrice) con.register(my_hist_data_handler, message.historicalData) con.connect() sleep(1) tickId = 1
from ib.opt import Connection, message ##?? import rpu_rp, rpInd, ibutiles, TicksUtile ####################### cpfname = EXE + 'entrycontroller.txt' def localreply_handler(msg): if msg.typeName == 'nextValidId': nextorderID = msg.orderId rpu_rp.WriteStringsToFile(TMP +'OrderIdsSavedlocalsigcreate.csv',str(nextorderID)+ ',') rpu_rp.WriteStringsToFileAppend(TMP + 'entryreplys',str(msg)) print str(msg) #################### testmode ='online' print 'mode is ' + testmode if testmode == 'online': global tws_conn tws_conn = Connection.create(port=7496, clientId=55) tws_conn.connect() tws_conn.register(ibutiles.error_handler, 'Error') tws_conn.registerAll(localreply_handler) ################### def get_orderid(): tws_conn.reqIds(100) sleep(1) for l in rpu_rp.CsvToLines(TMP + 'OrderIdsSavedlocalsigcreate.csv'): order_id = int(l[0]) return order_id ################################### def get_latest_tick(sym): RecentTickFile = DataDown + today + '.' + sym + '.RTtickslastquote.csv' tickline = rpu_rp.tail_array_to_array(rpu_rp.CsvToLines(RecentTickFile),1)[0] for f in tickline:
order.m_orderType = 'MKT' order.m_totalQuantity = quantity order.m_action = action return order #cid = 303 #Use the time as random cid cid=int(time.time()) while __name__ == "__main__": #because of there is no define for clientID in TWS,delete it here. conn = Connection.create(port=7496, clientId=999) #conn = Connection.create(port=7496) #registerAll(watcher) copy from github ...\IbPy\demo\fancy_marketdata conn.registerAll(watcher) conn.connect() oid = cid #USA Stock Exchange #cont = make_contract('TSLA', 'STK', 'SMART', 'SMART', 'USD') #offer = make_order('BUY', 1, 200) #HK Stock Exchange cont = make_contract('177', 'STK', 'SEHK', 'SEHK', 'HKD') offer = make_order('BUY', 2000, 10.00)
def connect_to_tws(self): self.tws_conn = Connection.create(port=self.port, clientId=self.client_id) self.tws_conn.connect() self.register_callback_functions()
def setup_connection(self): return Connection.create(port=4001, clientId=101) if self.is_use_gateway else ibConnection()
def __init__(self, host='localhost', port=4001, client_id=130, is_use_gateway=False, moving_window_period=dt.timedelta(seconds=60), test=False): self.test = test self.tz = pytz.timezone('Singapore') self.moving_window_period = moving_window_period self.ib_util = IBUtil() self.stocks_data = {} # Dictionary storing StockData objects.REFACTOR self.symbols = None # List of current symbols self.account_code = "" self.prices = None # Store last prices in a DataFrame self.ohlc = None # I need another store for minute data (I think) self.buffer = list() self.trade_qty = 0 #self.lock = Lock() self.traffic_light = Event() self.ohlc_ok = Lock() self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=10) self.timekeeper = None self.parser = None self.execution = None self.handler = None self.data_path = os.path.normpath(os.path.join(os.path.curdir,"data.csv")) self.ohlc_path = os.path.normpath(os.path.join(os.path.curdir,"ohlc.csv")) self.last_trim = None #range/trend flag self.flag = None self.event_market_on = Event() self.ml = MLcall() self.last_trim = None self.last_ml_call = None # self.last_trade = None # self.last_bid = None # self.last_ask = None # self.cur_mean = None # self.cur_sd = None # self.cur_zscore = None # Use ibConnection() for TWS, or create connection for API Gateway self.conn = Connection.create(host=host, port=port, clientId=client_id) #self.thread = threading.Thread(target=self.spawn()) #self.thread.start() if not self.test: self.handler = ExecutionHandler(self.conn) # #third handler should register properly si Dieu veut if self.test: self.__register_data_handlers(self.null_handler, self.__event_handler, self.null_handler) else: self.__register_data_handlers(self.handler.on_tick_event, self.__event_handler, self.handler._reply_handler) if self.test: self.order_template = self.create_contract("CL", "FUT", "NYMEX", "201606", "USD") else: self.order_template = self.handler.create_contract("CL", "FUT", "NYMEX", "201606", "USD")#todo duplicate with execution handler self.signal = None self.state = None
def __init__(self, client_id, port=7496): self.tws_conn = Connection.create(clientId=client_id, port=port)
def submit_order(ordertype, direction, orderid, stock, quantity): #ordertype = limit or market #direction = buy or sell #order id = unique identifier #stock = ticker #quantity = number of shares from ib.ext.Contract import Contract from ib.ext.Order import Order from ib.opt import Connection def error_handler(msg): print("Server Error:", msg) def server_handler(msg): print("Server Msg:", msg.typeName, "-", msg) def create_contract(symbol, sec_type, exch, prim_exch, curr): contract = Contract() contract.m_symbol = symbol contract.m_secType = sec_type contract.m_exchange = exch contract.m_primaryExch = prim_exch contract.m_currency = curr return contract def create_order(order_type, quantity, action): order = Order() order.m_action = action order.m_orderType = order_type order.m_totalQuantity = quantity order.m_lmtPrice = price return order #if __name__ == "__main__": client_id = 128 order_id = 488 ## iterate order id port = 7496 tws_conn = None #try: # Establish connection to TWS. tws_conn = Connection.create(port=port, clientId=client_id) tws_conn.connect() # Assign error handling function. tws_conn.register(error_handler, 'Error') # Assign server messages handling function. tws_conn.registerAll(server_handler) # Create AAPL contract and send order contract = create_contract(stock, 'STK', 'SMART', 'SMART', 'USD') # Go long 100 shares of AAPL tws_order = create_order(ordertype, quantity, direction) # Place order on IB TWS. tws_conn.placeOrder(order_id, contract, tws_order) #finally: # Disconnect from TWS if tws_conn is not None: tws_conn.disconnect()
def __init__(self, currency, strategy=None, frequency=60): """ initialize function :param currency: str, fx pair to trade, e.g. 'EUR' :param strategy: function(parameter contains self), execution strategy :param frequency: int, how many seconds to run strategy """ # store parameters self.currency = currency self.strategy = strategy self.frequency = frequency # create contract self.__contract = Contract() self.__contract.m_symbol = currency self.__contract.m_secType = 'CASH' self.__contract.m_exchange = 'IDEALPRO' self.__contract.m_primaryExch = 'IDEALPRO' self.__contract.m_currency = 'USD' # create empty order self.__order = Order() # connect to IB and register callback function self.conn = Connection.create(port=7497, clientId=1994) self.conn.connect() # self.conn.registerAll(self.reply_handler) self.conn.register(self.error_handler, message.Error) self.conn.register(self.bar_handler, message.realtimeBar) self.conn.register(self.snapshot_handler, message.tickPrice) self.conn.register(self.valid_id_handler, message.nextValidId) self.conn.register(self.time_handler, message.currentTime) self.conn.register(self.open_order_handler, message.orderStatus) self.conn.register(self.position_handler, message.position) self.conn.register(self.market_depth_handler, message.updateMktDepth) # get valid request ID and order ID self.__req_id = 1 self.__order_id = 1 self.conn.reqIds(1) # initialise other variables self.debug = False self.stop_ind = False self.order_time = None self.current_time = None self.position = 0 self.errors = [] self.bar_data = pd.DataFrame( columns=['DATETIME', 'OPEN', 'CLOSE', 'HIGH', 'LOW']) self.bid_price = None self.ask_price = None self.open_orders = {} self.min_price = MIN_PRICE[currency] # request real time data self.conn.reqRealTimeBars(tickerId=self.__req_id, contract=self.__contract, barSize=5, whatToShow='MIDPOINT', useRTH=1) self.__req_id += 1 self.conn.reqMktDepth(tickerId=self.__req_id, contract=self.__contract, numRows=1) self.__req_id += 1
if price is not None: order = Order() order.m_orderType = 'LMT' order.m_totalQuantity = quantity order.m_action = action order.m_lmtPrice = price else: order = Order() order.m_orderType = 'MKT' order.m_totalQuantity = quantity order.m_action = action return order cid = 567 while __name__ == "__main__": conn = Connection.create(port=7497, clientId=999) conn.registerAll(print_message_from_ib) conn.connect() oid = cid cont = make_contract('TSLA', 'STK', 'SMART', 'SMART', 'USD') offer = make_order('BUY', 1, 200) conn.placeOrder(oid, cont, offer) conn.disconnect() x = raw_input('enter to resend') cid += 1
contract.m_secType = 'STK' # for stock contract.m_exchange = 'ISLAND' # contract.m_primaryExch = 'ISLAND' # for NASDAQ contract.m_currency = 'USD' # 2. Construct order order = Order() if price is None: order.m_orderType = 'MKT' else: order.m_orderType = 'LMT' order.m_lmPrice = price order.m_totalQuantity = quantity order.m_action = action # 3. Place order ibConnection.placeOrder(orderId, contract, order) # smaller ID has Higher priority # 1. Establish connection ibConnection = Connection.create(port=7497, clientId=308) ibConnection.connect() # 2. Buy operate(orderId=20, ticker='NVDA', action='SELL', quantity=100) operate(orderId=21, ticker='TSLA', action='SELL', quantity=100) # 3. Disconnect ibConnection.disconnect()
def __init__(self, port=7496, clientId=100): self.reqId = 0 self.conn = Connection.create(port=port, clientId=clientId)
quantity - Integral number of assets to order action - 'BUY' or 'SELL'""" order = Order() order.m_orderType = order_type order.m_totalQuantity = quantity order.m_action = action return order if __name__ == "__main__": # Connect to the Trader Workstation (TWS) running on the # usual port of 7496, with a clientId of 100 # (The clientId is chosen by us and we will need # separate IDs for both the execution connection and # market data connection) tws_conn = Connection.create(port=4002, clientId=100) tws_conn.connect() # Assign the error handling function defined above # to the TWS connection tws_conn.register(error_handler, 'Error') # Assign all of the server reply messages to the # reply_handler function defined above tws_conn.registerAll(reply_handler) # Create an order ID which is 'global' for this session. This # will need incrementing once new orders are submitted. order_id = 1 # Create a contract in GOOG stock via SMART order routing
def dload_list(symbol_list,durmode): barlistall = bardict.keys() barlist =[] for b in barlistall: if modedict[b] != 'special' : barlist.append(b) ########################## def backupTickfiles(fname1): fname2 = fname1.replace('.csv','bu.csv') f1 = rpu_rp.CsvToLines(fname1) f2 = rpu_rp.CsvToLines(fname2) for line in f1: f2.append(line) rpu_rp.WriteArrayToCsvfile(fname2,f2) rpu_rp.WriteArrayToCsvfile(fname1,[]) ############# def error_handler(msg): if 'historicalData' in str(msg): print 'error probably pacing hist data' pass elif 'connection is OK' in str(msg): pass else: print "Server Error: %s" % msg ############# def historical_data_handler(msg): global newDataList fname = DataDown+ today + '.' + sym + '.' + bar.replace(' ','')+'.ddload.csv' if ('finished' in str(msg.date)) == False: ### keep building the list ## print (int(msg.date)) fstring = "%Y-%m-%d %H:%M:%S" dateold = localtime(int(msg.date)) tdate = strftime(fstring, dateold) if bar == '1 day': tdate = (str((int(msg.date))))[0:4] + '-' + str((int(msg.date)))[4:6]+ '-' + str((int(msg.date)))[6:8] + ' 23:59:58' ## print tdate ## print msg.date dataStr = '%s, %s, %s, %s, %s, %s, %s' % (sym, tdate, msg.open, msg.high, msg.low, msg.close, msg.volume) newDataList = newDataList + [dataStr] else: print 'next list' rpu_rp.WriteStringsToFile(fname,'') #flush the file for a in newDataList: if len(a) > 2: rpu_rp.WriteStringsToFileAppend(fname,a) newDataList = [] ########## def reply_handler(msg): if msg.typeName == 'historicalData': pass else: print "Server Response: %s, %s" % (msg.typeName, msg) #################### tws_conn = Connection.create(port=7496, clientId=109) tws_conn.connect() tws_conn.register(error_handler, 'Error') tws_conn.registerAll(reply_handler) tws_conn.register(historical_data_handler, message.historicalData) ####################################### trans_id = 0 if durmode == 'd': barlist = ['1day'] if durmode == '5secs': barlist =['5secs'] for sym in symbol_list: for bar in barlist: fname = DataDown+ today + '.' + sym + '.' + bar.replace(' ','')+'.ddload.csv' backupTickfiles(fname) ########## duration = bardict[bar] barspaced = bardictspaced[bar] contract = ibutiles.create_ticksym(trans_id,sym) ticktype = ticktypedict[sym] print bar, sym, duration,ticktype, barspaced tws_conn.reqHistoricalData(trans_id, contract, '', duration, barspaced, ticktype, 0, 2) trans_id = trans_id + 1 sleep(3) ############### print 'disconnecting from ib..' tws_conn.disconnect() for sym in symbol_list: for dura in barlist: throw_out_lastbar(sym,dura,today)
quantity - Integral number of assets to order action - 'BUY' or 'SELL'""" order = Order() order.m_orderType = order_type order.m_totalQuantity = quantity order.m_action = action return order if __name__ == "__main__": # Connect to the Trader Workstation (TWS) running on the # usual port of 7496, with a clientId of 100 # (The clientId is chosen by us and we will need # separate IDs for both the execution connection and # market data connection) tws_conn = Connection.create(port=4002, clientId=1) tws_conn.connect() # Assign the error handling function defined above # to the TWS connection tws_conn.register(error_handler, 'Error') # Assign all of the server reply messages to the # reply_handler function defined above tws_conn.registerAll(reply_handler) # Create an order ID which is 'global' for this session. This # will need incrementing once new orders are submitted. order_id = 1 # Create a contract in GOOG stock via SMART order routing
def create_order(order_type, quantity, action): order = Order() order.m_orderType = order_type order.m_totalQuantity = quantity order.m_action = action return order if __name__ == "__main__": client_id = 1 order_id = 122 port = 7496 tws_conn = None try: # Establish connection to TWS. tws_conn = Connection.create(port=port, clientId=client_id) tws_conn.connect() # Assign error handling function. tws_conn.register(error_handler, 'Error') # Assign server messages handling function. tws_conn.registerAll(server_handler) # Create AAPL contract and send order aapl_contract = create_contract('AAPL', 'STK', 'SMART', 'SMART', 'USD')
def connect(port,clientID): tws_conn = Connection.create(port=port, clientId=client_id) tws_conn.connect() return tws_conn
######## elif msg.typeName == 'updateMktDepth': ######## onerow.append(timenow) ######## rpu_rp.WriteArrayToCsvfileAppend(DataDown +today+'.'+sym+ '.RTMktDepth.csv',[onerow]) else: print str(msg) rpu_rp.WriteStringsToFileAppend(TMP + 'replys.RTticks', str(msg)) ######## if msg.typeName == 'tickPrice' and fieldnum == '1': ######## ##<tickPrice tickerId=1, field=4, price=1927.0, canAutoExecute=0> ######## onerow.append(timenow) ######## rpu_rp.WriteArrayToCsvfile(DataDown +today+'.'+sym+ '.RTtickslastquoteTicker.csv',[onerow]) ################################# print 'Connecting to Live DATAFEED,depth, and per tick trade counter...please wait' tws_conn = Connection.create( port=7496, clientId=178) #need separate IDs for both the execution connection and tws_conn.connect() tws_conn.register(ibutiles.error_handler, 'Error') tws_conn.registerAll(reply_handler) ########################## cycletime = 60 ## will need to be increase for more products because of delay cyclesperhour = 3600 / cycletime loopmax = cyclesperhour * 10 # = allday loop = 1 ################ reqID = 1 symid = 0 strike = 22 expiry = '22' ##############
# The port number has the same value as defined in our API settings of TWS port = 7497 # The client_id variable is our assigned integer that identifies # the instance of the client communicating with TWS client_id = 1 # The order_id variable is our assigned integer that identifies # the order queue number sent to TWS. Each new order requires # this value to be incremented sequentially order_id = 122 tws_conn = None try: # create a IB connection instance tws_conn = Connection.create(port=port, clientId=client_id) # make a connection tws_conn.connect() # register the error handler tws_conn.register(error_handler, 'Error') # register the server handler tws_conn.registerAll(server_handler) # create a contract aapl_contract = create_contract( 'AAPL', 'STK', 'SMART', 'SMART', 'USD' ) # create an oder to long 10 shares of AAPL
value = msg.price quotearray[5] = symTickerIddict[msg.tickerId] if msg.typeName == 'tickSize': fnum = msg.field value =msg.size quotearray[int(fielddict[str(fnum)])] = value if msg.typeName == 'tickSnapshotEnd': sym = quotearray[5] quotearray[6] = today quotearray[0] = datetime.now().time().isoformat() linearray = [] linearray.append(quotearray) rpu_rp.WriteArrayToCsvfileAppend(DataDown +today+'.'+sym+ '.ticksnaps.csv',linearray) rpu_rp.WriteStringsToFileAppend(TMP +'replys.snapshots',str(msg)) ################################# tws_conn = Connection.create(port=7496, clientId=108) #need separate IDs for both the execution connection and tws_conn.connect() tws_conn.register(ibutiles.error_handler, 'Error') tws_conn.registerAll(local_reply_handler) ########################## symTickerIddict ={} def create_contract_dictionary(ordid,sym): contract = ibutiles.create_ticksym(ordid,sym) contractdict.update({sym : contract}) symTickerIddict.update({ordid : sym}) ## print contractdict ########################## ordid =0 contractdict ={} for sym in symbol_list: ordid+=1
order.m_orderType = order_type order.m_totalQuantity = quantity order.m_action = action order.m_account = account return order # ib_api_demo.py if __name__ == "__main__": # Connect to the Trader Workstation (TWS) running on the # usual port of 7497, with a clientId of 000 # (The clientId is chosen by us and we will need # separate IDs for both the execution connection and # market data connection) tws_conn = Connection.create(port=7497, clientId=000) tws_conn.connect() # Assign the error handling function defined above # to the TWS connection tws_conn.register(error_handler, 'Error') # Assign all of the server reply messages to the # reply_handler function defined above tws_conn.registerAll(reply_handler) # Create an order ID which is 'global' for this session. This # will need incrementing once new orders are submitted. order_id = 503 # has to change each time # Create a contract in GOOG stock via SMART order routing
tdate = strftime(fstring, dateold) if len(msg.date) == 8 : tdate = (str((int(msg.date))))[0:4] + '-' + str((int(msg.date)))[4:6]+ '-' + str((int(msg.date)))[6:8] + ' 23:59:58' dataStr = '%s, %s, %s, %s, %s, %s, %s' % (sym, tdate, msg.open, msg.high, msg.low, msg.close, msg.volume) newDataList = newDataList + [dataStr] else: print 'next list' rpu_rp.WriteStringsToFile(fname,'') #flush the file for a in newDataList: if len(a) > 2: rpu_rp.WriteStringsToFileAppend(fname,a) newDataList = [] ########## newDataList = [] print 'connecting hdownload flex' tws_conn = Connection.create(port=7496, clientId=125) tws_conn.connect() tws_conn.register(Mod_ibutiles.error_handler, 'Error') tws_conn.registerAll(reply_handler) tws_conn.register(historical_data_handler, message.historicalData) ####################################### def dload(symlist,barlist,strikelist,expirylist): print symlist,barlist global bar, sym trans_id = 0 strikelist = [1] expirylist = [1] for sym in symlist: print sym for bar in barlist: for strike in strikelist:
def __init__(self, host='localhost', port=4001, client_id=130, is_use_gateway=False, moving_window_period=dt.timedelta(seconds=60), test=False): logging.basicConfig(format='%(asctime)s %(message)s') self.test_logger = logging.getLogger('hftModelLogger') self.test_logger.setLevel(logging.INFO) self.test = test self.tz = pytz.timezone('Singapore') self.moving_window_period = moving_window_period self.ib_util = IBUtil() self.symbols = None # List of current symbols self.account_code = "" self.prices = None # Store last prices in a DataFrame self.ohlc = None # I need another store for minute data (I think) self.buffer = list() self.trade_qty = 0 self.traffic_light = Event() self.ohlc_ok = Lock() self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=6) self.timekeeper = None self.parser = None self.execution = None self.strategy = None self.handler = None self.data_path = os.path.normpath(os.path.join(os.path.curdir,"data.csv")) self.ohlc_path = os.path.normpath(os.path.join(os.path.curdir,"ohlc.csv")) self.flag = None self.event_market_on = Event() self.ml = MLcall() self.last_trim = None self.last_ml_call = None self.cur_mean = None self.cur_sd = None # Use ibConnection() for TWS, or create connection for API Gateway self.conn = Connection.create(host=host, port=port, clientId=client_id) if not self.test: self.handler = ExecutionHandler(self.conn) #third handler should register properly si Dieu veut if self.test: self.__register_data_handlers(self.null_handler, self.__event_handler, self.null_handler) else: self.__register_data_handlers(self.handler.on_tick_event, self.__event_handler, self.handler._reply_handler) if self.test: self.order_template = self.create_contract(settings.SYMBOL, settings.SECURITY, settings.EXCHANGE, settings.EXPIRY, settings.CURRENCY) else: self.order_template = self.handler.create_contract(settings.SYMBOL, settings.SECURITY, settings.EXCHANGE, settings.EXPIRY, settings.CURRENCY) self.signal = None self.state = None