Ejemplo n.º 1
0
    def __init__(self, callback):
        """
        Create like this
        callback = IBWrapper()
        client=IBclient(callback)
        """

        tws = EPosixClientSocket(callback)
        (host, port, clientid) = return_IB_connection_info()
        tws.eConnect(host, port, clientid)

        self.tws = tws
        self.cb = callback
Ejemplo n.º 2
0
	def __init__(self, callback, clientid=None, accountid="DU202715"):
		"""
		Create like this
		callback = IBWrapper()
		client=IBclient(callback)
		"""

		tws = EPosixClientSocket(callback)
		(host, port, clientid)=return_IB_connection_info(clientid)
		tws.eConnect(host, port, clientid)

		self.tws=tws
		self.cb=callback
		self.accountid = accountid
		self.clientid = clientid
Ejemplo n.º 3
0
    def __init__(self, callback, accountid="DU305658"):
        """
        Create like this
        callback = IBWrapper()
        client=IBclient(callback)
        """

        tws = EPosixClientSocket(callback)
        (host, port, clientid) = return_IB_connection_info()
        tws.eConnect(host, port, clientid)

        self.tws = tws
        self.accountid = accountid
        self.cb = callback
        self.logger = logging.getLogger("renaissance")
Ejemplo n.º 4
0
    def openOrder(self, orderID, contract, order, orderState):

        print "Order opened for %s" % contract.symbol


prompt = raw_input("WARNING: This example will place an order on your IB "
                   "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:
Ejemplo n.º 5
0
    def error(self, id, errCode, errString):
        global clientid
        global tws
        global connection_state
        global pacing
        global last_time
        global cooldowntime

        s = "IB[{}]: {}".format(errCode, errString)
        if id > -1:
            s += " (ID: {})".format(id)
        logging.debug(s)

        if errCode == ErrorCode.clientid_in_use:
            logging.info(
                "Client ID {} in use, reconnecting ...".format(clientid))
            clientid += 1
            tws = EPosixClientSocket(self)
            tws.eConnect("", 7496, clientid)
        elif errCode == ErrorCode.md_connection_ok:
            logging.info("IB[{}]: {}".format(errCode, errString))
            api_started.set()
        # TODO: use a better string here!
        elif errCode == ErrorCode.historical_data_error and "Historical data request pacing violation" in errString:
            logging.info(
                "Historical data pacing violation: retrying last batch and start using pacing between data requests..."
            )
            logging.info(errString)
            if not pacing:
                pacing = 10
            dt = prev_last_time.strftime("%Y%m%d %H:%M:%S")
            logging.info("Cooling down for {} seconds...".format(cooldowntime))
            sleep(cooldowntime)
            cooldowntime += 15  #  sometimes we just need to cool down for a longer time
            tws.reqHistoricalData(0, contract, dt, duration, barsize, datatype,
                                  rth_only, 1)
        elif errCode == ErrorCode.historical_data_error and "invalid step" in errString:
            logging.info("IB[{}]: {}".format(errCode, errString))
            historical_data_received.set()
        elif errCode == ErrorCode.historical_data_error and "HMDS query returned no data" in errString:
            logging.info("IB[{}]: {}".format(errCode, errString))
            historical_data_received.set()
        elif (errCode == ErrorCode.historical_data_error and "Trader Workstation exited" in errString) or \
                errCode == ErrorCode.cannot_connect_to_tws:
            logging.info("IB[{}]: {}".format(errCode, errString))
            tws.exited = True
            historical_data_received.set()
        # requesting historical data from period too long time ago
        elif errCode == ErrorCode.error_validating_request and "Historical data queries on this contract requesting any data earlier than" in errString:
            dt = prev_last_time.strftime(dt_format)
            logging.info(
                "IB cannot provide data from period ending {}, it's too far back in the history."
                .format(dt))
            historical_data_received.set()
        elif errCode == ErrorCode.error_validating_request:
            s = "IB[{}]: {}".format(errCode, errString)
            if id > -1:
                s += " (ID: {})".format(id)
            logging.fatal(s)
            historical_data_received.set()
        elif errCode == ErrorCode.connection_lost:
            # TODO: some logic to retry after connection has been momentarily lost, and eventually give up...
            logging.info("Connection lost, saving data end aborting...")
            if not output_file:
                sys.exit(ExitCode.error_can_continue)
            historical_data_received.set()
        elif errCode == ErrorCode.no_security_def_found:
            logging.info("IB[{}]: {}".format(errCode, errString))
            if not output_file:
                sys.exit(ExitCode.error_can_continue)
            historical_data_received.set()
        else:
            s = "IB[{}]: {}".format(errCode, errString)
            if id > -1:
                s += " (ID: {})".format(id)
            logging.info(s)
Ejemplo n.º 6
0
 def __init__(self):
     self.callback = ArtemisIBWrapper()
     self.tws = EPosixClientSocket(self.callback)
     self.tws.eConnect("", 7496, 44, poll_interval=1)
Ejemplo n.º 7
0
    def __init__(self, callback):
        tws = EPosixClientSocket(callback)
        (host, port, clientid) = return_IB_connection_info()
        tws.eConnect(host, port, clientid)

        self.tws = tws
Ejemplo n.º 8
0
 def connect(self, port=7496):
     if self.is_connected():
         self.disconnect()
     cid = self.get_next_cid()
     self.tws = EPosixClientSocket(self.wrapper)
     self.tws.eConnect('', port, cid)
Ejemplo n.º 9
0
        if date[:8] == 'finished':
            print("History request complete")
            self.got_history.set()
        else:
            date = datetime.strptime(date, "%Y%m%d").strftime("%d %b %Y")
            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, reconnect_auto=True)

# Connect to tws running on localhost
if not tws.eConnect("", 7496, 42):
    raise RuntimeError('Failed to connect to TWS')

# Simple contract for GOOG
contract = Contract()
contract.exchange = "SMART"
contract.symbol = "GOOG"
contract.secType = "STK"
contract.currency = "USD"
today = datetime.today()

print("Requesting historical data for %s" % contract.symbol)