Exemple #1
0
class IbApi(EWrapper):
    """"""
    data_filename = "ib_contract_data.db"
    data_filepath = str(get_file_path(data_filename))

    local_tz = get_localzone()

    def __init__(self, gateway: BaseGateway):
        """"""
        super().__init__()

        self.gateway = gateway
        self.gateway_name = gateway.gateway_name

        self.status = False

        self.reqid = 0
        self.orderid = 0
        self.clientid = 0
        self.history_reqid = 0
        self.account = ""
        self.ticks = {}
        self.orders = {}
        self.accounts = {}
        self.contracts = {}

        self.tick_exchange = {}
        self.subscribed = {}
        self.data_ready = False

        self.history_req = None
        self.history_condition = Condition()
        self.history_buf = []

        self.client = EClient(self)

    def connectAck(self):  # pylint: disable=invalid-name
        """
        Callback when connection is established.
        """
        self.status = True
        self.gateway.write_log("IB TWS连接成功")

        self.load_contract_data()

        self.data_ready = False

    def connectionClosed(self):  # pylint: disable=invalid-name
        """
        Callback when connection is closed.
        """
        self.status = False
        self.gateway.write_log("IB TWS连接断开")

    def nextValidId(self, orderId: int):  # pylint: disable=invalid-name
        """
        Callback of next valid orderid.
        """
        super().nextValidId(orderId)

        if not self.orderid:
            self.orderid = orderId

    def currentTime(self, time: int):  # pylint: disable=invalid-name
        """
        Callback of current server time of IB.
        """
        super().currentTime(time)

        dt = datetime.fromtimestamp(time)
        time_string = dt.strftime("%Y-%m-%d %H:%M:%S.%f")

        msg = f"服务器时间: {time_string}"
        self.gateway.write_log(msg)

    def error(self, reqId: TickerId, errorCode: int, errorString: str):  # pylint: disable=invalid-name
        """
        Callback of error caused by specific request.
        """
        super().error(reqId, errorCode, errorString)
        if reqId == self.history_reqid:
            self.history_condition.acquire()
            self.history_condition.notify()
            self.history_condition.release()

        msg = f"信息通知,代码:{errorCode},内容: {errorString}"
        self.gateway.write_log(msg)

        # Market data server is connected
        if errorCode == 2104 and not self.data_ready:
            self.data_ready = True

            self.client.reqCurrentTime()

            reqs = list(self.subscribed.values())
            self.subscribed.clear()
            for req in reqs:
                self.subscribe(req)

    def tickPrice(  # pylint: disable=invalid-name
            self, reqId: TickerId, tickType: TickType, price: float,
            attrib: TickAttrib):
        """
        Callback of tick price update.
        """
        super().tickPrice(reqId, tickType, price, attrib)

        if tickType not in TICKFIELD_IB2VT:
            return

        tick = self.ticks[reqId]
        name = TICKFIELD_IB2VT[tickType]
        setattr(tick, name, price)

        # Update name into tick data.
        contract = self.contracts.get(tick.vt_symbol, None)
        if contract:
            tick.name = contract.name

        # Forex of IDEALPRO and Spot Commodity has no tick time and last price.
        # We need to calculate locally.
        exchange = self.tick_exchange[reqId]
        if exchange is Exchange.IDEALPRO or "CMDTY" in tick.symbol:
            tick.last_price = (tick.bid_price_1 + tick.ask_price_1) / 2
            tick.datetime = datetime.now(self.local_tz)
        self.gateway.on_tick(copy(tick))

    def tickSize(self, reqId: TickerId, tickType: TickType, size: int):  # pylint: disable=invalid-name
        """
        Callback of tick volume update.
        """
        super().tickSize(reqId, tickType, size)

        if tickType not in TICKFIELD_IB2VT:
            return

        tick = self.ticks[reqId]
        name = TICKFIELD_IB2VT[tickType]
        setattr(tick, name, size)

        self.gateway.on_tick(copy(tick))

    def tickString(self, reqId: TickerId, tickType: TickType, value: str):  # pylint: disable=invalid-name
        """
        Callback of tick string update.
        """
        super().tickString(reqId, tickType, value)

        if tickType != TickTypeEnum.LAST_TIMESTAMP:
            return

        tick = self.ticks[reqId]
        dt = datetime.fromtimestamp(int(value))
        tick.datetime = self.local_tz.localize(dt)

        self.gateway.on_tick(copy(tick))

    def orderStatus(  # pylint: disable=invalid-name
        self,
        orderId: OrderId,
        status: str,
        filled: float,
        remaining: float,
        avgFillPrice: float,
        permId: int,
        parentId: int,
        lastFillPrice: float,
        clientId: int,
        whyHeld: str,
        mktCapPrice: float,
    ):
        """
        Callback of order status update.
        """
        super().orderStatus(
            orderId,
            status,
            filled,
            remaining,
            avgFillPrice,
            permId,
            parentId,
            lastFillPrice,
            clientId,
            whyHeld,
            mktCapPrice,
        )

        orderid = str(orderId)
        order = self.orders.get(orderid, None)
        if not order:
            return

        order.traded = filled

        # To filter PendingCancel status
        order_status = STATUS_IB2VT.get(status, None)
        if order_status:
            order.status = order_status

        self.gateway.on_order(copy(order))

    def openOrder(  # pylint: disable=invalid-name
        self,
        orderId: OrderId,
        ib_contract: Contract,
        ib_order: Order,
        orderState: OrderState,
    ):
        """
        Callback when opening new order.
        """
        super().openOrder(orderId, ib_contract, ib_order, orderState)

        orderid = str(orderId)
        order = OrderData(
            symbol=generate_symbol(ib_contract),
            exchange=EXCHANGE_IB2VT.get(ib_contract.exchange, Exchange.SMART),
            type=ORDERTYPE_IB2VT[ib_order.orderType],
            orderid=orderid,
            direction=DIRECTION_IB2VT[ib_order.action],
            volume=ib_order.totalQuantity,
            gateway_name=self.gateway_name,
        )

        if order.type == OrderType.LIMIT:
            order.price = ib_order.lmtPrice
        elif order.type == OrderType.STOP:
            order.price = ib_order.auxPrice

        self.orders[orderid] = order
        self.gateway.on_order(copy(order))

    def updateAccountValue(  # pylint: disable=invalid-name
            self, key: str, val: str, currency: str, accountName: str):
        """
        Callback of account update.
        """
        super().updateAccountValue(key, val, currency, accountName)

        if not currency or key not in ACCOUNTFIELD_IB2VT:
            return

        accountid = f"{accountName}.{currency}"
        account = self.accounts.get(accountid, None)
        if not account:
            account = AccountData(accountid=accountid,
                                  gateway_name=self.gateway_name)
            self.accounts[accountid] = account

        name = ACCOUNTFIELD_IB2VT[key]
        setattr(account, name, float(val))

    def updatePortfolio(  # pylint: disable=invalid-name
        self,
        contract: Contract,
        position: float,
        marketPrice: float,
        marketValue: float,
        averageCost: float,
        unrealizedPNL: float,
        realizedPNL: float,
        accountName: str,
    ):
        """
        Callback of position update.
        """
        super().updatePortfolio(
            contract,
            position,
            marketPrice,
            marketValue,
            averageCost,
            unrealizedPNL,
            realizedPNL,
            accountName,
        )

        if contract.exchange:
            exchange = EXCHANGE_IB2VT.get(contract.exchange, None)
        elif contract.primaryExchange:
            exchange = EXCHANGE_IB2VT.get(contract.primaryExchange, None)
        else:
            exchange = Exchange.SMART  # Use smart routing for default

        if not exchange:
            msg = f"存在不支持的交易所持仓{generate_symbol(contract)} {contract.exchange} {contract.primaryExchange}"
            self.gateway.write_log(msg)
            return

        try:
            ib_size = int(contract.multiplier)
        except ValueError:
            ib_size = 1
        price = averageCost / ib_size

        pos = PositionData(
            symbol=generate_symbol(contract),
            exchange=exchange,
            direction=Direction.NET,
            volume=position,
            price=price,
            pnl=unrealizedPNL,
            gateway_name=self.gateway_name,
        )
        self.gateway.on_position(pos)

    def updateAccountTime(self, timeStamp: str):  # pylint: disable=invalid-name
        """
        Callback of account update time.
        """
        super().updateAccountTime(timeStamp)
        for account in self.accounts.values():
            self.gateway.on_account(copy(account))

    def contractDetails(self, reqId: int, contractDetails: ContractDetails):  # pylint: disable=invalid-name
        """
        Callback of contract data update.
        """
        super().contractDetails(reqId, contractDetails)

        # Generate symbol from ib contract details
        ib_contract = contractDetails.contract
        if not ib_contract.multiplier:
            ib_contract.multiplier = 1

        symbol = generate_symbol(ib_contract)

        # Generate contract
        contract = ContractData(
            symbol=symbol,
            exchange=EXCHANGE_IB2VT[ib_contract.exchange],
            name=contractDetails.longName,
            product=PRODUCT_IB2VT[ib_contract.secType],
            size=int(ib_contract.multiplier),
            pricetick=contractDetails.minTick,
            net_position=True,
            history_data=True,
            stop_supported=True,
            gateway_name=self.gateway_name,
        )

        if contract.vt_symbol not in self.contracts:
            self.gateway.on_contract(contract)

            self.contracts[contract.vt_symbol] = contract
            self.save_contract_data()

    def execDetails(self, reqId: int, contract: Contract,
                    execution: Execution):  # pylint: disable=invalid-name
        """
        Callback of trade data update.
        """
        super().execDetails(reqId, contract, execution)

        dt = datetime.strptime(execution.time, "%Y%m%d  %H:%M:%S")
        dt = self.local_tz.localize(dt)

        trade = TradeData(
            symbol=generate_symbol(contract),
            exchange=EXCHANGE_IB2VT.get(contract.exchange, Exchange.SMART),
            orderid=str(execution.orderId),
            tradeid=str(execution.execId),
            direction=DIRECTION_IB2VT[execution.side],
            price=execution.price,
            volume=execution.shares,
            datetime=dt,
            gateway_name=self.gateway_name,
        )

        self.gateway.on_trade(trade)

    def managedAccounts(self, accountsList: str):
        """
        Callback of all sub accountid.
        """
        super().managedAccounts(accountsList)

        if not self.account:
            for account_code in accountsList.split(","):
                self.account = account_code

        self.gateway.write_log(f"当前使用的交易账号为{self.account}")
        self.client.reqAccountUpdates(True, self.account)

    def historicalData(self, reqId: int, ib_bar: IbBarData):
        """
        Callback of history data update.
        """
        dt = datetime.strptime(ib_bar.date, "%Y%m%d %H:%M:%S")
        dt = self.local_tz.localize(dt)

        bar = BarData(symbol=self.history_req.symbol,
                      exchange=self.history_req.exchange,
                      datetime=dt,
                      interval=self.history_req.interval,
                      volume=ib_bar.volume,
                      open_price=ib_bar.open,
                      high_price=ib_bar.high,
                      low_price=ib_bar.low,
                      close_price=ib_bar.close,
                      gateway_name=self.gateway_name)

        self.history_buf.append(bar)

    def historicalDataEnd(self, reqId: int, start: str, end: str):
        """
        Callback of history data finished.
        """
        self.history_condition.acquire()
        self.history_condition.notify()
        self.history_condition.release()

    def connect(self, host: str, port: int, clientid: int, account: str):
        """
        Connect to TWS.
        """
        if self.status:
            return

        self.host = host
        self.port = port
        self.clientid = clientid
        self.account = account

        self.client.connect(host, port, clientid)
        self.thread = Thread(target=self.client.run)
        self.thread.start()

    def check_connection(self):
        """"""
        if self.client.isConnected():
            return

        if self.status:
            self.close()

        self.client.connect(self.host, self.port, self.clientid)

        self.thread = Thread(target=self.client.run)
        self.thread.start()

    def close(self):
        """
        Disconnect to TWS.
        """
        if not self.status:
            return

        self.status = False
        self.client.disconnect()

    def subscribe(self, req: SubscribeRequest):
        """
        Subscribe tick data update.
        """
        if not self.status:
            return

        if req.exchange not in EXCHANGE_VT2IB:
            self.gateway.write_log(f"不支持的交易所{req.exchange}")
            return

        # Filter duplicate subscribe
        if req.vt_symbol in self.subscribed:
            return
        self.subscribed[req.vt_symbol] = req

        # Extract ib contract detail
        ib_contract = generate_ib_contract(req.symbol, req.exchange)
        if not ib_contract:
            self.gateway.write_log("代码解析失败,请检查格式是否正确")
            return

        # Get contract data from TWS.
        self.reqid += 1
        self.client.reqContractDetails(self.reqid, ib_contract)

        # Subscribe tick data and create tick object buffer.
        self.reqid += 1
        self.client.reqMktData(self.reqid, ib_contract, "", False, False, [])

        tick = TickData(
            symbol=req.symbol,
            exchange=req.exchange,
            datetime=datetime.now(self.local_tz),
            gateway_name=self.gateway_name,
        )
        self.ticks[self.reqid] = tick
        self.tick_exchange[self.reqid] = req.exchange

    def send_order(self, req: OrderRequest):
        """
        Send a new order.
        """
        if not self.status:
            return ""

        if req.exchange not in EXCHANGE_VT2IB:
            self.gateway.write_log(f"不支持的交易所:{req.exchange}")
            return ""

        if req.type not in ORDERTYPE_VT2IB:
            self.gateway.write_log(f"不支持的价格类型:{req.type}")
            return ""

        self.orderid += 1

        ib_contract = generate_ib_contract(req.symbol, req.exchange)
        if not ib_contract:
            return ""

        ib_order = Order()
        ib_order.orderId = self.orderid
        ib_order.clientId = self.clientid
        ib_order.action = DIRECTION_VT2IB[req.direction]
        ib_order.orderType = ORDERTYPE_VT2IB[req.type]
        ib_order.totalQuantity = req.volume
        ib_order.account = self.account

        if req.type == OrderType.LIMIT:
            ib_order.lmtPrice = req.price
        elif req.type == OrderType.STOP:
            ib_order.auxPrice = req.price

        self.client.placeOrder(self.orderid, ib_contract, ib_order)
        self.client.reqIds(1)

        order = req.create_order_data(str(self.orderid), self.gateway_name)
        self.gateway.on_order(order)
        return order.vt_orderid

    def cancel_order(self, req: CancelRequest):
        """
        Cancel an existing order.
        """
        if not self.status:
            return

        self.client.cancelOrder(int(req.orderid))

    def query_history(self, req: HistoryRequest):
        """"""
        self.history_req = req

        self.reqid += 1

        ib_contract = generate_ib_contract(req.symbol, req.exchange)

        if req.end:
            end = req.end
            end_str = end.strftime("%Y%m%d %H:%M:%S")
        else:
            end = datetime.now(self.local_tz)
            end_str = ""

        delta = end - req.start
        days = min(delta.days, 180)  # IB only provides 6-month data
        duration = f"{days} D"
        bar_size = INTERVAL_VT2IB[req.interval]

        if req.exchange == Exchange.IDEALPRO:
            bar_type = "MIDPOINT"
        else:
            bar_type = "TRADES"

        self.history_reqid = self.reqid
        self.client.reqHistoricalData(self.reqid, ib_contract, end_str,
                                      duration, bar_size, bar_type, 0, 1,
                                      False, [])

        self.history_condition.acquire()  # Wait for async data return
        self.history_condition.wait()
        self.history_condition.release()

        history = self.history_buf
        self.history_buf = []  # Create new buffer list
        self.history_req = None

        return history

    def load_contract_data(self):
        """"""
        f = shelve.open(self.data_filepath)
        self.contracts = f.get("contracts", {})
        f.close()

        for contract in self.contracts.values():
            self.gateway.on_contract(contract)

        self.gateway.write_log("本地缓存合约信息加载成功")

    def save_contract_data(self):
        """"""
        f = shelve.open(self.data_filepath)
        f["contracts"] = self.contracts
        f.close()
Exemple #2
0
class IBBroker(Broker):
    """
    Interactive Brokers Broker class. Main purpose of this class is to connect to the API of IB broker and send
    the orders. It provides the functionality, which allows to retrieve a.o. the currently open positions and the
    value of the portfolio.

    Parameters
    -----------
    contract_ticker_mapper: IBContractTickerMapper
        mapper which provides the functionality that allows to map a ticker from any data provider
        (BloombergTicker, PortaraTicker etc.) onto the contract object from the Interactive Brokers API
    clientId: int
        id of the Broker client
    host: str
        IP address
    port: int
        socket port
    """
    def __init__(self,
                 contract_ticker_mapper: IBContractTickerMapper,
                 clientId: int = 0,
                 host: str = "127.0.0.1",
                 port: int = 7497):
        super().__init__(contract_ticker_mapper)
        self.logger = ib_logger.getChild(self.__class__.__name__)
        # Lock that synchronizes entries into the functions and makes sure we have a synchronous communication
        # with the client
        self.lock = Lock()
        self.orders_placement_lock = Lock()
        self.waiting_time = 30  # expressed in seconds
        # Lock that informs us that wrapper received the response
        self.action_event_lock = Event()
        self.wrapper = IBWrapper(self.action_event_lock,
                                 contract_ticker_mapper)
        self.client = EClient(wrapper=self.wrapper)
        self.clientId = clientId
        self.client.connect(host, port, self.clientId)

        # Run the client in the separate thread so that the execution of the program can go on
        # now we will have 3 threads:
        # - thread of the main program
        # - thread of the client
        # - thread of the wrapper
        thread = Thread(target=self.client.run)
        thread.start()

        # This will be released after the client initialises and wrapper receives the nextValidOrderId
        if not self._wait_for_results():
            raise ConnectionError("IB Broker was not initialized correctly")

    def get_portfolio_value(self) -> float:
        with self.lock:
            request_id = 1
            self._reset_action_lock()
            self.client.reqAccountSummary(request_id, 'All', 'NetLiquidation')
            wait_result = self._wait_for_results()
            self.client.cancelAccountSummary(request_id)

            if wait_result:
                return self.wrapper.net_liquidation
            else:
                error_msg = 'Time out while getting portfolio value'
                self.logger.error(error_msg)
                raise BrokerException(error_msg)

    def get_portfolio_tag(self, tag: str) -> float:
        with self.lock:
            request_id = 2
            self._reset_action_lock()
            self.client.reqAccountSummary(request_id, 'All', tag)
            wait_result = self._wait_for_results()
            self.client.cancelAccountSummary(request_id)

            if wait_result:
                return self.wrapper.tmp_value
            else:
                error_msg = 'Time out while getting portfolio tag: {}'.format(
                    tag)
                self.logger.error(error_msg)
                raise BrokerException(error_msg)

    def get_positions(self) -> List[BrokerPosition]:
        with self.lock:
            self._reset_action_lock()
            self.wrapper.reset_position_list()
            self.client.reqPositions()

            if self._wait_for_results():
                return self.wrapper.position_list
            else:
                error_msg = 'Time out while getting positions'
                self.logger.error(error_msg)
                raise BrokerException(error_msg)

    def get_liquid_hours(self, contract: IBContract) -> QFDataFrame:
        """ Returns a QFDataFrame containing information about liquid hours of the given contract. """
        with self.lock:
            self._reset_action_lock()
            request_id = 3
            self.client.reqContractDetails(request_id, contract)

            if self._wait_for_results():
                contract_details = self.wrapper.contract_details
                liquid_hours = contract_details.tradingHours.split(";")
                liquid_hours_df = QFDataFrame.from_records([
                    hours.split("-")
                    for hours in liquid_hours if not hours.endswith("CLOSED")
                ],
                                                           columns=[
                                                               "FROM", "TO"
                                                           ])
                for col in liquid_hours_df.columns:
                    liquid_hours_df[col] = to_datetime(liquid_hours_df[col],
                                                       format="%Y%m%d:%H%M")

                liquid_hours_df.name = contract_details.contract.symbol
                return liquid_hours_df

            else:
                error_msg = 'Time out while getting contract details'
                self.logger.error(error_msg)
                raise BrokerException(error_msg)

    def get_contract_details(self, contract: IBContract) -> ContractDetails:
        with self.lock:
            self._reset_action_lock()
            request_id = 4
            self.client.reqContractDetails(request_id, contract)

            if self._wait_for_results():
                return self.wrapper.contract_details
            else:
                error_msg = 'Time out while getting contract details'
                self.logger.error(error_msg)
                raise BrokerException(error_msg)

    def place_orders(self, orders: Sequence[Order]) -> Sequence[int]:
        with self.orders_placement_lock:
            open_order_ids = {o.id for o in self.get_open_orders()}

            order_ids_list = []
            for order in orders:
                self.logger.info('Placing Order: {}'.format(order))
                order_id = self._execute_single_order(
                    order) or self._find_newly_added_order_id(
                        order, open_order_ids)
                if order_id is None:
                    error_msg = f"Not able to place order: {order}"
                    self.logger.error(error_msg)
                    raise BrokerException(error_msg)
                else:
                    order_ids_list.append(order_id)
            return order_ids_list

    def cancel_order(self, order_id: int):
        with self.lock:
            self.logger.info('Cancel order: {}'.format(order_id))
            self._reset_action_lock()
            self.wrapper.set_cancel_order_id(order_id)
            self.client.cancelOrder(order_id)

            if not self._wait_for_results():
                error_msg = 'Time out while cancelling order id {} : \n'.format(
                    order_id)
                self.logger.error(error_msg)
                raise OrderCancellingException(error_msg)

    def get_open_orders(self) -> List[Order]:
        with self.lock:
            self._reset_action_lock()
            self.wrapper.reset_order_list()
            self.client.reqOpenOrders()

            if self._wait_for_results():
                return self.wrapper.order_list
            else:
                error_msg = 'Timeout while getting open orders'
                self.logger.error(error_msg)
                raise BrokerException(error_msg)

    def cancel_all_open_orders(self):
        """
        There is no way to check if cancelling of all orders was finished.
        One can only get open orders and confirm that the list is empty
        """
        with self.lock:
            self.client.reqGlobalCancel()
            self.logger.info('cancel_all_open_orders')

    def stop(self):
        """ Stop the Broker client and disconnect from the interactive brokers. """
        with self.lock:
            self.client.disconnect()
            self.logger.info(
                "Disconnecting from the interactive brokers client")

    def _find_newly_added_order_id(self, order: Order,
                                   order_ids_existing_before: Set[int]):
        """ Given the list of order ids open before placing the given order, try to compute the id of the recently
         placed order. """
        orders_matching_given_order = {
            o.id
            for o in self.get_open_orders() if o == order
        }
        order_ids = orders_matching_given_order.difference(
            order_ids_existing_before)
        return next(iter(order_ids)) if len(order_ids) == 1 else None

    def _execute_single_order(self, order) -> Optional[int]:
        with self.lock:
            order_id = self.wrapper.next_order_id()

            self._reset_action_lock()
            self.wrapper.set_waiting_order_id(order_id)

            ib_contract = self.contract_ticker_mapper.ticker_to_contract(
                order.ticker)
            ib_order = self._to_ib_order(order)

            self.client.placeOrder(order_id, ib_contract, ib_order)
            if self._wait_for_results(10):
                return order_id

    def _wait_for_results(self, waiting_time: Optional[int] = None) -> bool:
        """ Wait for self.waiting_time """
        waiting_time = waiting_time or self.waiting_time
        wait_result = self.action_event_lock.wait(waiting_time)
        return wait_result

    def _reset_action_lock(self):
        """ threads calling wait() will block until set() is called"""
        self.action_event_lock.clear()

    def _to_ib_order(self, order: Order):
        ib_order = IBOrder()
        ib_order.action = 'BUY' if order.quantity > 0 else 'SELL'
        ib_order.totalQuantity = abs(order.quantity)

        ib_order = self._set_execution_style(ib_order, order.execution_style)

        time_in_force = order.time_in_force
        tif_str = self._map_to_tif_str(time_in_force)
        ib_order.tif = tif_str

        return ib_order

    def _map_to_tif_str(self, time_in_force):
        if time_in_force == TimeInForce.GTC:
            tif_str = "GTC"
        elif time_in_force == TimeInForce.DAY:
            tif_str = "DAY"
        elif time_in_force == TimeInForce.OPG:
            tif_str = "OPG"
        else:
            raise ValueError("Not supported TimeInForce {tif:s}".format(
                tif=str(time_in_force)))

        return tif_str

    def _set_execution_style(self, ib_order, execution_style):
        if isinstance(execution_style, MarketOrder):
            ib_order.orderType = "MKT"
        elif isinstance(execution_style, StopOrder):
            ib_order.orderType = "STP"
            ib_order.auxPrice = execution_style.stop_price
        return ib_order
Exemple #3
0
class IBBroker(Broker):
    def __init__(self):
        self.logger = ib_logger.getChild(self.__class__.__name__)
        # lock that synchronizes entries into the functions and
        # makes sure we have a synchronous communication with client
        self.lock = Lock()
        self.waiting_time = 30  # expressed in seconds
        # lock that informs us that wrapper received the response
        self.action_event_lock = Event()
        self.wrapper = IBWrapper(self.action_event_lock)
        self.client = EClient(wrapper=self.wrapper)
        self.client.connect("127.0.0.1", 7497, clientId=0)

        # run the client in the separate thread so that the execution of the program can go on
        # now we will have 3 threads:
        # - thread of the main program
        # - thread of the client
        # - thread of the wrapper
        thread = Thread(target=self.client.run)
        thread.start()

        # this will be released after the client initialises and wrapper receives the nextValidOrderId
        if not self._wait_for_results():
            raise ConnectionError("IB Broker was not initialized correctly")

    def get_portfolio_value(self) -> float:
        with self.lock:
            request_id = 1
            self._reset_action_lock()
            self.client.reqAccountSummary(request_id, 'All', 'NetLiquidation')
            wait_result = self._wait_for_results()
            self.client.cancelAccountSummary(request_id)

            if wait_result:
                return self.wrapper.net_liquidation
            else:
                error_msg = 'Time out while getting portfolio value'
                self.logger.error('===> {}'.format(error_msg))
                raise BrokerException(error_msg)

    def get_portfolio_tag(self, tag: str) -> float:
        with self.lock:
            request_id = 2
            self._reset_action_lock()
            self.client.reqAccountSummary(request_id, 'All', tag)
            wait_result = self._wait_for_results()
            self.client.cancelAccountSummary(request_id)

            if wait_result:
                return self.wrapper.tmp_value
            else:
                error_msg = 'Time out while getting portfolio tag: {}'.format(tag)
                self.logger.error('===> {}'.format(error_msg))
                raise BrokerException(error_msg)

    def get_positions(self) -> List[Position]:
        with self.lock:
            self._reset_action_lock()
            self.wrapper.reset_position_list()
            self.client.reqPositions()

            if self._wait_for_results():
                return self.wrapper.position_list
            else:
                error_msg = 'Time out while getting positions'
                self.logger.error('===> {}'.format(error_msg))
                raise BrokerException(error_msg)

    def place_orders(self, orders: Sequence[Order]) -> Sequence[int]:
        order_ids_list = []
        for order in orders:
            self.logger.info('Placing Order: {}'.format(order))
            order_id = self._execute_single_order(order)
            order_ids_list.append(order_id)

        return order_ids_list

    def cancel_order(self, order_id: int):
        with self.lock:
            self.logger.info('cancel_order: {}'.format(order_id))
            self._reset_action_lock()
            self.wrapper.set_cancel_order_id(order_id)
            self.client.cancelOrder(order_id)

            if not self._wait_for_results():
                error_msg = 'Time out while cancelling order id {} : \n'.format(order_id)
                self.logger.error('===> {}'.format(error_msg))
                raise OrderCancellingException(error_msg)

    def get_open_orders(self) -> List[Order]:
        with self.lock:
            self._reset_action_lock()
            self.wrapper.reset_order_list()
            self.client.reqOpenOrders()

            if self._wait_for_results():
                return self.wrapper.order_list
            else:
                error_msg = 'Time out while getting orders'
                self.logger.error('===> {}'.format(error_msg))
                raise BrokerException(error_msg)

    def cancel_all_open_orders(self):
        """
        There is now way to check if cancelling of all orders was finished.
        One can only get open orders and confirm that the list is empty
        """
        with self.lock:
            self.client.reqGlobalCancel()
            self.logger.info('cancel_all_open_orders')

    def _execute_single_order(self, order) -> int:
        with self.lock:
            order_id = self.wrapper.next_order_id()

            self._reset_action_lock()
            self.wrapper.set_waiting_order_id(order_id)

            ib_contract = self._to_ib_contract(order.contract)
            ib_order = self._to_ib_order(order)
            self.client.placeOrder(order_id, ib_contract, ib_order)

            if self._wait_for_results():
                return order_id
            else:
                error_msg = 'Time out while placing the trade for: \n\torder: {}'.format(order)
                self.logger.error('===> {}'.format(error_msg))
                raise BrokerException(error_msg)

    def _wait_for_results(self) -> bool:
        """ Wait for self.waiting_time """
        wait_result = self.action_event_lock.wait(self.waiting_time)
        return wait_result

    def _reset_action_lock(self):
        """ threads calling wait() will block until set() is called"""
        self.action_event_lock.clear()

    def _to_ib_contract(self, contract: Contract):
        ib_contract = IBContract()
        ib_contract.symbol = contract.symbol
        ib_contract.secType = contract.security_type
        ib_contract.exchange = contract.exchange
        return ib_contract

    def _to_ib_order(self, order: Order):
        ib_order = IBOrder()

        if order.quantity > 0:
            ib_order.action = 'BUY'
        else:
            ib_order.action = 'SELL'

        ib_order.totalQuantity = abs(order.quantity)

        execution_style = order.execution_style
        self._set_execution_style(ib_order, execution_style)

        time_in_force = order.time_in_force
        tif_str = self._map_to_tif_str(time_in_force)
        ib_order.tif = tif_str

        return ib_order

    def _map_to_tif_str(self, time_in_force):
        if time_in_force == TimeInForce.GTC:
            tif_str = "GTC"
        elif time_in_force == TimeInForce.DAY:
            tif_str = "DAY"
        elif time_in_force == TimeInForce.OPG:
            tif_str = "OPG"
        else:
            raise ValueError("Not supported TimeInForce {tif:s}".format(tif=str(time_in_force)))

        return tif_str

    def _set_execution_style(self, ib_order, execution_style):
        if isinstance(execution_style, MarketOrder):
            ib_order.orderType = "MKT"
        elif isinstance(execution_style, StopOrder):
            ib_order.orderType = "STP"
            ib_order.auxPrice = execution_style.stop_price