Beispiel #1
0
    def __init__(self, host, port, client_id, account):
        self.host = host
        self.port = port
        self.open_orders = {}
        self.open_positions = {}
        self.req_id = 0
        self.account = account
        EWrapper.__init__(self)
        EClient.__init__(self, wrapper=self)
        self.connect(host, port, client_id)
        self.startApi()
        tickThread(101010, self).start()
        if self.isConnected():
            1
        else:
            while self.isConnected() == False:

                print('Sleeping 40 seconds')
                sleep(40)
                self.disconnect()
                self.done = False
                self.connect(host, port, client_id)
                self.startApi()
                tickThread(101010, self).start()
        self.reqAccountUpdates(True, account)
Beispiel #2
0
    def __init__(self, addr, port, client_id):
        """
        CONSTRUCTOR
        
        Parameters
        ----------
        addr : str
            IP where TWS or IBGateway is running.
        port : int
            Firewall port where is allowed the connection
        client_id : int
            Number beetween 1 and 32. This allow several clients connected to
            a TWS session. This number should be fixed for the admin in the server
            For test, 1 is enought.
            
        """
        self.client_id = client_id
        self.address = addr
        self.port = port
        
        EClient. __init__(self, self)
        EWrapper.__init__(self)

        # Connect to TWS
        self.connect(addr, port, client_id)
        
        # Launch the client thread
        thread = Thread(target=self.run)
        thread.start()
        
        time.sleep(1)
Beispiel #3
0
    def __init__(self, host, port, clientId):
        EWrapper.__init__(self)
        EClient.__init__(self, wrapper=self)
        self.connect(host, port, clientId)

        self.reqId = 0
        self.tickHandler = handlers.IBTickHandler()
    def __init__(
        self,
        receiver: str = "workstation",
        trading_mode: str = "paper",
        socket_port: Optional[int] = None,
        client_id: Optional[int] = None,
    ):
        Subscribable.__init__(self)
        EWrapper.__init__(self)
        EClient.__init__(self, wrapper=self)

        self._ip_address = "127.0.0.1"
        if socket_port is not None:
            self._socket_port = socket_port
        elif receiver == "workstation" and trading_mode == "paper":
            self._socket_port = 7497
        elif receiver == "workstation" and trading_mode == "live":
            raise ValueError("Socket port not yet set.")
        elif receiver == "gateway" and trading_mode == "paper":
            raise ValueError("Socket port not yet set.")
        elif receiver == "gateway" and trading_mode == "live":
            raise ValueError("Socket port not yet set.")
        else:
            raise ValueError(
                f"Unrecognized socket port configuration receiver={receiver}"
                f" trading_mode={trading_mode}. Please consult the"
                f" documentation for valid values."
            )

        if client_id is None:
            self._client_id = _get_client_id()
        else:
            self._client_id = client_id
 def historicalDataEnd(self, reqId: int, start: str, end: str):
     """ Marks the ending of the historical bars reception. """
     EWrapper.historicalDataEnd(self, reqId, start, end)
     if self._file:
         self._file.close()
         self._file = None
     self.tws2gui.put('END')
Beispiel #6
0
    def __init__(self, toTws, toGui,toWat):
        EWrapper.__init__(self)
        TestClient.__init__(self, wrapper=self)

        self.idmarketdata=0#temporary

        self.toTws = toTws
        self.toGui = toGui
        self.toWat = toWat


        self.nKeybInt = 0
        self.started = False
        #self._lastId = None
        self._lastId = 0
        self._file = None
        #self.stepSize={'1 sec':'1800 S','5 sec':'3600 S','10 secs':'14400 S','30 secs':'28800 S','1 min':'2 D','30 mins':'1 M','1 day':'1 Y'}

        #self.oneStock=OneStock(None)
        self.downloadHistInfo={} #will keep the donwload info
        self.nextIDconID={}#to be able to translate nextID to conID
        #self.stop5secnextID={}#will keep the nextID to be able to stop 5 sec
        self.stop_reqTickByTickData={}#will keep the nextID to be able to stop the MarketData
        self.stop_reqRealTimeBars={} #stop 5 sec bars

        self.realTickData={} #will keep the data
Beispiel #7
0
 def __init__(self):
     EWrapper.__init__(self)
     self.data = {}
     self.avail_funds = None
     self.scanner_instr = {}
     self.scanner_instr_all = {}
     self.daily_pnl = 0
Beispiel #8
0
    def __init__(self):
        EWrapper.__init__(self)  # Instantiate a wrapper object
        EClient.__init__(self, wrapper=self)  # Instantiate a client object

        # CONNECTION OPTIONS

        self.socket_port = 7497  # Gateway: 4002; Workstation: 7497
        self.ip_address = "127.0.0.1"
        self.client_id = 0

        # APP VARIABLES

        self.reqID = None  # Stores the next valid request id
        self.account = None  # Stores the account number

        # CONNECT TO SERVER

        self.connect(self.ip_address,
                     self.socket_port,
                     clientId=self.client_id)  # Connect to server
        print(
            f"serverVersion:{self.serverVersion()} connectionTime:{self.twsConnectionTime()}\n"
        )  # Check connection

        # Request frozen market data in case live is not available.
        # Different market data subscriptions give you access to different information
        # https://interactivebrokers.github.io/tws-api/market_data_type.html#gsc.tab=0
        self.reqMarketDataType(4)
Beispiel #9
0
    def __init__(self, host, port, client_id):
        EWrapper.__init__(self)
        EClient.__init__(self, self)
        self._next_valid_id = None
        self.code_contract_map: Dict[str, Contract] = {}
        self.client_status_callbacks: List[ClientStatusCallback] = []
        self.try_connect(host, port, client_id)

        # 启动ping线程,如果与服务器的连接丢失,则会尝试重新连接
        def ping():
            # retry_count = 0
            while True:
                try:
                    if self.connState != EClient.CONNECTED or not self.reader.is_alive(
                    ):
                        logging.info("尝试重新连接")
                        self.try_connect(host, port, client_id)
                except:
                    import traceback
                    logging.error("{}".format(traceback.format_exc()))

                time.sleep(10)

        threading.Thread(name="ib_ping", target=ping).start()
        logging.info("IBClient 初始化完成")
Beispiel #10
0
    def __init__(self, host='tws', port=7496, clientId=0, demo=True):
        EWrapper.__init__(self)
        EClient.__init__(self, wrapper=self)

        self.demo = demo
        self.dwrapper = IBWrapper(app=self)
        self._thread = None
        self._connection_specs = (host, port, clientId)
Beispiel #11
0
 def __init__(self):
     super().__init__()
     EWrapper.__init__(self)
     EClient.__init__(self, wrapper=self)
     self.nextValidOrderId = None
     self.simplePlaceOid = None
     self.connState = None
     self.conn = None
Beispiel #12
0
    def __init__(self, msgHandler=None, time_zone=ClockController.time_zone):
        EWrapper.__init__(self)
        self.msgHandler = msgHandler
        self.default_tz = pytz.timezone(time_zone)

        if msgHandler is None:
            self.resolved_contract = []
            self.contractDetailsIsObtained = False
Beispiel #13
0
    def __init__(self, host, port, clientId):
        EWrapper.__init__(self)
        EClient.__init__(self, wrapper=self)
        self.connect(host, port, clientId)
        logger.info('Interactive Brokers is connected.')

        self.reqId = 0
        self.historicBarHandler = handlers.IBHistoricBarHandler()
    def error(self, reqId: TickerId, errorCode: int, errorString: str):
        """This event is called when there is an error with the
        communication or when TWS wants to send a message to the client."""
        EWrapper.error(self, reqId, errorCode, errorString)

        # Error messages with codes (2104, 2106, 2107, 2108) are not real errors but information messages
        if errorCode not in (2104, 2106, 2107, 2108):
            self.tws2gui.put(f'ERROR {errorCode}: {errorString}')
Beispiel #15
0
    def __init__(self):
        EWrapper.__init__(self)
        EClient.__init__(self, wrapper=self)

        # Reference Fields
        self.connected = False
        self.order_id = 0
        self.nasdaq_last_price = 0
Beispiel #16
0
 def tickEFP(self, reqId:TickerId, tickType:TickType, basisPoints:float,
             formattedBasisPoints:str, totalDividends:float,
             holdDays:int, futureLastTradeDate:str, dividendImpact:float,
             dividendsToLastTradeDate:float):
     EWrapper.tickEFP(reqId, tickType,basisPoints,
             formattedBasisPoints, totalDividends,
             holdDays, futureLastTradeDate, dividendImpact,
             dividendsToLastTradeDate)
     print('tickEFP')
Beispiel #17
0
    def __init__(self, listeners):
        EWrapper.__init__(self)

        self.listeners = listeners
        self.next_valid_order_id = -1
        self._pending_orders = dict()
        self._has_valid_id = threading.Event()
        self._lock = threading.RLock()
        self._positions = None
Beispiel #18
0
 def __init__(self):
     EWrapper.__init__(self)
     EClient.__init__(self)
     self.connect(addr, port, client_id)
     self.order_id = None
     thread = Thread(target=self.run)
     thread.start()
     client = EClient(wrapper)
     client.connect("")
Beispiel #19
0
 def __init__(self):
     EWrapper.__init__(self)
     self.historical_data = []
     self.historicalDataRequestIds = []
     self.historicalDataReceivedIds = []
     self.earliestTradeDate = ''
     self.endOfHistoricalData = False
     self.positions = {}
     self.positionsEnd = False
Beispiel #20
0
    def historicalDataEnd(self, reqId: int, start: str, end: str):
        """ Marks the ending of the historical bars reception. """
        #msg=toMessage('DownloadFinish')
        #self.toGui.put(msg)

        EWrapper.historicalDataEnd(self, reqId, start, end)

        #translate back
        #print("translate back",reqId,self.nextIDconID[reqId])
        conID=self.nextIDconID[reqId]
        #print('reqId after transalation ',conID)

        if self.downloadHistInfo[conID].whatToDownload=='histnew5secOneTime':
            msg = toMessage('5secHist')
            #we must send the reaId besides the list
            msg.obj =[conID,self.downloadHistInfo[conID]]
            self.toWat.put(msg) # we send to watch,

            print('histnew5secOneTime - finished',conID)

            #must clear the downloadHistInfo
            self.downloadHistInfo.pop(conID)
            ## maybe we should send some message to gui too to inform the user that we are ready

            return

        ret=self.dbLite.addOneStock(self.downloadHistInfo[conID])

        start = self.downloadHistInfo[conID].oneStock.bars1min[0].date

        del self.downloadHistInfo[conID].oneStock.bars1min[:]

        if ret=='stop': #we don't need to download anymore in case of a newhist

            if self.downloadHistInfo[conID].whatToDownload=='histnewLevel1':
                msg=toMessage('histnewLevel1End')
                msg.obj=conID
                self.toGui.put(msg) #let's anounce that we can go to level 2
                #print('hist new Level1 end')
            self.downloadHistInfo.pop(conID)  # removed from dictionary - no sens to stay there
            print('finish new download')
            return

        #delete all the bars
        self.downloadHistInfo[conID].count += 1

        if self.downloadHistInfo[conID].count>=10 and self.downloadHistInfo[conID].whatToDownload=='histold':
            #we already download 60 for history so do not send anymore messages

            self.downloadHistInfo.pop(conID)
            return

        self.downloadHistInfo[conID].dateToDownload = start
        msg=toMessage('HistFinish')
        msg.obj=self.downloadHistInfo[conID]
        self.toGui.put(msg)
        return
Beispiel #21
0
    def __init__(self, addr, port, client_id):
        EWrapper.__init__(self)
        EClient.__init__(self, self)

        # Connect to TWS API
        self.connect(addr, port, client_id)

        # Launch the client thread
        thread = threading.Thread(target=self.run)
        thread.start()
Beispiel #22
0
 def __init__(self):
     EWrapper.__init__(self)
     EClient.__init__(self, wrapper=self)
     self.nKeybInt = 0
     self.started = False
     self.nextValidOrderId = None
     self.permId2ord = {}
     self.reqId2nErr = collections.defaultdict(int)
     self.globalCancelOnly = False
     self.simplePlaceOid = None
Beispiel #23
0
 def __init__(self, underlyingContract, Instricklist, filepath):
     EWrapper.__init__(self)
     iclient.__init__(self, wrapper=self)
     self.filepath = filepath
     self.quotedatadict = {}
     self.reqID_contract_dict = {}
     self.underlyingContract = underlyingContract
     self.refresher = threading.Timer(10, self.refreshfun)
     self.expirations = ''
     self.Instricklist = Instricklist
    def __init__(self, gui2tws, tws2gui):
        EWrapper.__init__(self)
        IBClient.__init__(self, wrapper=self)

        self.gui2tws = gui2tws
        self.tws2gui = tws2gui
        self.nKeybInt = 0
        self.started = False
        self._lastId = None
        self._file = None
Beispiel #25
0
    def orderStatus(self, orderId: OrderId, status: str, filled: float,
                    remaining: float, avgFillPrice: float, permId: int,
                    parentId: int, lastFillPrice: float, clientId: int,
                    whyHeld: str):
        EWrapper.orderStatus(self, orderId, status, filled, remaining,
                             avgFillPrice, permId, parentId, lastFillPrice,
                             clientId, whyHeld)

        if status == "Filled":
            self.lastOrderDone = True
Beispiel #26
0
    def __init__(self):
        EWrapper.__init__(self)
        EClient.__init__(self, wrapper=self)

        self.positions = []
        self.positions_done = False
        self.available_funds = None
        self.available_funds_currency = None
        self.account_summary_done = False
        self.connection_failed = False
Beispiel #27
0
 def __init__(self):
     EWrapper.__init__(self)
     EClient.__init__(self, self)
     self.nextValidOrderId = 0
     self.account_buying_power_usd = TOTAL_BUY_POWER
     self.candles_data = []  # Initialize list to store candles
     self.time_queue = queue.Queue()  # Store time log
     self.errors_queue = queue.Queue()  # Store error message
     self.stock_df = pd.DataFrame(
         columns=["symbol", "trade_ID", "action", "quantity", "price"])
     self.reqIds(-1)  # Send request to server, ask for orderId. -1 default.
Beispiel #28
0
 def __init__(self):
     EWrapper.__init__(self)
     EClient.__init__(self, wrapper=self)
     # ! [socket_init]
     self.nKeybInt = 0
     self.started = False
     self.nextValidOrderId = None
     self.permId2ord = {}
     self.globalCancelOnly = False
     self.simplePlaceOid = None
     self._my_errors = {}
Beispiel #29
0
 def __init__(self, contractlist:list, filepath):
     EWrapper.__init__(self)
     iclient.__init__(self, wrapper=self)
     self.contractlist = contractlist
     self.reqID = 0
     self.csvpath = filepath
     self.optreqIDdict = {}
     self.underlyingIDdict = {}
     self.reqOptParamsIDdict = {}
     self.optionsquotesdict = {}
     self.refresher = threading.Timer(10, self.refreshfun)
    def nextValidId(self, orderId: int):
        """
        Callback
        orderId -- First unused order id provided by TWS
        Use reqIds() to request this info
        """
        EWrapper.nextValidId(self, orderId)
        logging.debug(f'Setting next order Id: {orderId}')

        self._lastId = orderId - 1
        self._onStart()