예제 #1
0
    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)
예제 #2
0
    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)
예제 #3
0
파일: test IB.py 프로젝트: yayaya123/Python
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()
예제 #4
0
 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()
예제 #5
0
파일: tws.py 프로젝트: distagon/txTrader
 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()
예제 #6
0
파일: ibutil.py 프로젝트: fraka6/pytrade
 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
예제 #7
0
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()
예제 #8
0
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 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."
예제 #10
0
파일: testIbPy.py 프로젝트: TimonPeng/pi314
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)
예제 #11
0
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()
예제 #13
0
    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
예제 #14
0
파일: ats_model.py 프로젝트: amitkp9/ATS
    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)
        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 = 303

while __name__ == "__main__":

    conn = Connection.create(port=7497, clientId=9898)
    conn.connect()
    oid = cid
    cont = make_contract('APLE', 'STK', 'SMART', 'SMART', 'USD')
    offer = make_order('BUY', 1, 200)
    conn.placeOrder(oid, cont, offer)
    offer_2 = make_order('SELL', 1, 200)
    conn.placeOrder(oid, cont, offer_2)

    cont = make_contract('EUR', 'STK', 'IDEALPRO', 'IDEALPRO', 'USD')
    offer = make_order('BUY', 1, 200)
    conn.placeOrder(oid, cont, offer)
    conn.disconnect()
    x = input('enter to resend')
    cid += 1
 def setup_connection(self):
     return Connection.create(port=4001, clientId=101) if self.is_use_gateway else ibConnection()
예제 #17
0
    if msg.typeName == 'realtimeBar':
        reqid=(((str(msg)).split()[1]).split('=')[1]).replace(',','')
        sym=symTickerIddict[reqid]
        onerow = (str(msg)).split(',')
##        print onerow
        cleanonerow = TicksUtile.clean_RTTick5secBars(onerow,sym)
        rpu_rp.WriteArrayToCsvfileAppend(DataDown +today+'.'+sym+ '.'+tickfiletag+'.csv',[onerow])
        rpu_rp.WriteArrayToCsvfile(DataDown +today+'.'+sym+ '.RTtickslastquotenew.csv',[cleanonerow])
    else:
        print str(msg)
        rpu_rp.WriteStringsToFileAppend(TMP +'replys.'+tickfiletag,str(msg))
#################################
print 'Connecting to Live DATAFEED...please wait'
print 'Collecting 5Second Tick Bars in realtime for the following symbols...'
print symbol_list
tws_conn = Connection.create(port=7496, clientId=164) #need separate IDs for both the execution connection and
tws_conn.connect()
tws_conn.register(ibutiles.error_handler, 'Error')
tws_conn.registerAll(RTBar_reply_handler)
##########################
cycletime = 120 ## will need to be increase for more products because of delay
loopmax = 300000 # = allday
loop = 1
################
reqID=1
symid =0
strike=22
expiry = '22'
for sym in symbol_list:
    symid+=1
    contract = ibutiles.create_contract(sym,strike,expiry)
 def connect_to_tws(self):
     self.tws_conn = Connection.create(port=self.port,
                                       clientId=self.client_id)
     self.tws_conn.connect()
예제 #19
0
def connect(port, clientID):
    tws_conn = Connection.create(port=port, clientId=client_id)
    tws_conn.connect()
    return tws_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]
예제 #21
0
 def __init__(self, client_id, port=7496):
     self.tws_conn = Connection.create(clientId=client_id, port=port)
예제 #22
0
        order = Order()
        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)
예제 #23
0
        cleanonerow = TicksUtile.format_RTTickoneline_to_5secBars(onerow, sym)
        rpu_rp.WriteArrayToCsvfileAppend(
            DataDown + today + '.' + sym + '.RTticks.csv', [cleanonerow])
        rpu_rp.WriteArrayToCsvfile(
            DataDown + today + '.' + sym + '.RTtickslastquote.csv',
            [cleanonerow])
    else:
        if 'connection is OK' in str(msg):
            pass
        else:
            print str(msg)
    rpu_rp.WriteStringsToFileAppend(replyfname, str(msg))


#################################
tws_conn = Connection.create(port=7496, clientId=179)
tws_conn.connect()
tws_conn.register(ibutiles.error_handler, 'Error')
tws_conn.registerAll(reply_handler)
tws_conn.register(reply_handler)

##########################
symTickerIddict = {}
symid = 1
for sym in symbol_list2:
    print sym, symid
    symTickerIddict.update({str(symid): sym})
    symid += 1


def start_tickers():
예제 #24
0
        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)
예제 #25
0
    :return:
    """
    print("Server Error:", msg)


def server_handler(msg):
    """
    A function that prints the messages from Interactive Brokers
    :param msg: the error message
    :return:
    """
    print("Server Msg:", msg.typeName, "-", msg)


if __name__ == "__main__":
    port = 7497
    client_id = 1
    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)
    finally:
        if tws_conn is not None:
            tws_conn.disconnect()
 def setup_connection(self):
     return Connection.create(port=4001, clientId=101) if self.is_use_gateway else ibConnection()
예제 #27
0
    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()
예제 #28
0
 def connect_to_tws(self):
     self.tws_conn = Connection.create(port=self.port,
                                       clientId=self.client_id)
     self.tws_conn.connect()
예제 #29
0
파일: test_order.py 프로젝트: fluxdark/kod
    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 __init__(self, port=7496, clientId=100):
     self.reqId = 0
     self.conn = Connection.create(port=port, clientId=clientId)
예제 #31
0
    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
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)
예제 #33
0
파일: common.py 프로젝트: gongqingyi/stock
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
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')
예제 #35
0
    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
예제 #36
0
        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:ARCA'
    qqq.m_currency = 'USD'
    logger.debug('Requesting historical data')
    conn.reqHistoricalData(1, qqq, '', '1 D', '1 day', 'TRADES', 0, 1)
예제 #37
0
    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


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)
    con = Connection.create(port=7496, clientId=100)
    con.connect()
    # Assign the error handling function defined above
    # to the TWS connection
    con.register(error_handler, 'Error')
    # Assign all of the server reply messages to the
    # reply_handler function defined above
    con.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

    #con.registerAll(watcher)
    # 註冊我們對回傳的 historicalData 要採取的 handler
    con.register(my_hist_data_handler, message.historicalData)
예제 #38
0
        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
예제 #39
0
 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()
예제 #40
0
        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:
예제 #41
0
    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