Esempio n. 1
0
    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)
Esempio n. 2
0
    def __init__(self, host, port, client_id):
        super().__init__()
        cli = EClient(self)
        self.cli = cli
        self.host = host
        self.port = port
        self.client_id = client_id
        self.account_subscriber = None
        self.tick_subscriber = None
        self.market_data_subscriber: EWrapper = None
        self._next_valid_id = None
        self.code_contract_map = {}
        self.client_status_callbacks: List[ClientStatusCallback] = []
        self.try_connect()

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

                time.sleep(10)

        threading.Thread(name="ib_ping", target=ping).start()
Esempio n. 3
0
    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")
Esempio n. 4
0
 def options(self, expiry, strike, right, database="Quotes", table=None):
     table = self.symbol if table == None else table
     global app
     app = EClient(
         Wrapper(self.qdate, self.symbol, self.currency, database, table,
                 expiry, strike, right, self.window))
     app.connect(host="127.0.0.1", port=4001, clientId=123)
     app.run()
Esempio n. 5
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("")
Esempio n. 6
0
 def equities(self, database="Quotes", table="Spot"):
     global app
     app = EClient(
         Wrapper(self.qdate,
                 self.symbol,
                 self.currency,
                 database,
                 table,
                 window=self.window))
     app.connect(host="127.0.0.1", port=4001, clientId=123)
     app.run()
Esempio n. 7
0
 def __init__(self, host, port, client_id, initial_cash: float):
     super().__init__(initial_cash)
     client = EClient(self)
     self.client = client
     self.positions = {}
     self.orders: List[Order] = []
     self._next_valid_id = None
     self.ib_order_id_to_order: Dict[int, Order] = {}
     self.contract_code_to_detail = {}
     client.connect(host, port, client_id)
     import threading
     threading.Thread(name="ib_msg_consumer", target=client.run).start()
Esempio n. 8
0
 def start_app(self, host: str, port: int, client_id: int):
     """ Start a connection ton IB TWS application in a background thread and confirm connection is successful.
     :param host: Hostname to connect to, usually 127.0.0.1
     :param port: Port to connect to, configurable and differs for live vs paper trading.
     :param client_id: Client ID setting for the TWS API
     """
     self._app = EClient(wrapper=self)
     self.connected.clear()
     self.next_request_id = 0
     self._app.connect(host, port, client_id)
     self.thread = Thread(target=self._app.run, daemon=True)
     self.thread.start()
     # connectAck will set the connected event once called
     self.connected.wait(timeout=self.timeout)
Esempio n. 9
0
 def __init__(self, clientId):
     super().__init__()
     self.req_id_base = 1000
     self.index = 0
     self.cache_data = {}
     # self.products = sorted(products, key=lambda x: random.random(), reverse=False)
     self.products = products
     self.req_id_map = {}
     # self.req_id = 0
     self.callback_map = {}
     self.thread = None
     self.ready = None
     self.clientId = clientId or 1
     # global client
     client = EClient(wrapper=self)
     self.client = client
     self.klines = None
Esempio n. 10
0
    def __init__(self, ip_addr='127.0.0.1', port=7497, clientId=1):

        # Wrapper Methods
        def nextValidId(reqId):
            q.put(reqId)

        def connectionClosed():
            print('CONNECTION HAS CLOSED')

        def error(reqId, errorCode: int, errorString: str):
            if errorCode != 2104 and errorCode != 2106:
                print("Error. Id: ", reqId, " Code: ", errorCode, " Msg: ",
                      errorString)
                if errorCode == 10167 and 'Displaying delayed market data' in errorString:
                    pass
                elif reqId != -1:
                    self.data_errors_q.put((errorString, reqId))
                if 'pacing violation' in errorString:
                    self.slowdown = True

        # Wrapper Methods End

        self.wrapper = EWrapper()
        self.client = EClient(self.wrapper)

        self.client.connect(ip_addr, port, clientId)
        self.ip_addr = ip_addr
        self.my_port = port
        self.my_clientId = clientId
        self.resetData()

        # Wrap wrapper methods
        self.wrap(error)
        self.wrap(connectionClosed)
        self.wrap(nextValidId)

        q = queue.Queue()
        self._thread = Thread(target=self.client.run)
        self._thread.start()
        # Once we get a reqID, we know we can start
        self._reqId = q.get()
Esempio n. 11
0
    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")
        continue

    my_wrapper = MyWrapper()

    my_wrapper.current_date = start_date
    my_wrapper.sampling_rate = "5"  # minutes
    my_wrapper.symbol = stock_symbol

    while datetime.datetime.strptime(my_wrapper.current_date,
                                     time_format) > datetime.datetime.strptime(
                                         end_date, time_format):
        try:
            # the duplication of the following three lines allows us to extract continuous data on the same stock
            # another effect of this implementation is at least two rounds of data extraction
            # to sum up, the following code works but sometimes will extract extra data - its OK by me :)
            app = EClient(my_wrapper)
            my_wrapper.did_something = False
            app.connect('127.0.0.1', 7496, clientId=123)
            main()
            if not my_wrapper.did_something:
                # if my_wrapper didn't change the 'just_starting' flag - it is stuck and we need to stop querying the stock
                break
        finally:
            if my_wrapper.the_app_is_down:
                print('It seems like the app is down, closing connection')
                exit()
            else:
                app = EClient(my_wrapper)
                my_wrapper.did_something = False
                app.connect('127.0.0.1', 7496, clientId=123)
                main()
Esempio n. 13
0
def cancel_data(request):
    # cancel_stock = TestApp()
    wrapper = EWrapper()
    cancel_data = EClient(wrapper)
    cancel_data.disconnect()
    return render(request, 'ib_api/cancel_data.html')
Esempio n. 14
0
        super().contractDetailsEnd(reqId)
        print("ContractDetailsEnd. ", reqId, "\n")

    def tickPrice(self, reqId, tickType, price, attrib):
        super().tickPrice(reqId, tickType, price, attrib)
        print("Tick Price. Ticker Id:", reqId, "tickType:", tickType, "Price:",
              price, "CanAutoExecute:", attrib.canAutoExecute, "PastLimit",
              attrib.pastLimit)

    def tickSnapshotEnd(self, reqId):
        super().tickSnapshotEnd(reqId)
        print("TickSnapshotEnd:", reqId)


wrapper = MyWrapper()
app = EClient(wrapper)
app.connect("127.0.0.1", 7497, clientId=0)
print("serverVersion:%s connectionTime:%s" %
      (app.serverVersion(), app.twsConnectionTime()))

from ibapi.contract import Contract
contract = Contract()
contract.symbol = "XAUUSD"
contract.secType = "CMDTY"
contract.exchange = "SMART"
contract.currency = "USD"

app.reqMktData(1, contract, "", False, False, [])
app.run()

if __name__ == '__main__':
Esempio n. 15
0
 def connect(self, host, port):
     client = EClient(wrapper)
     client.connect(host, port, -)
     thread = Thread(target=self.run)
     thread.start()
Esempio n. 16
0
    def historicalDataEnd(self, reqId: int, start: str, end: str):
        #8 data is finished
        print("HistoricalDataEnd. ReqId:", reqId, "from", start, "to", end)
        #9 this is the logical end of your program
        app.disconnect()
        print("finished")

    def error(self, reqId, errorCode, errorString):
        # these messages can come anytime.
        print("Error. Id: ", reqId, " Code: ", errorCode, " Msg: ",
              errorString)

    def start(self):
        queryTime = (datetime.datetime.today() -
                     datetime.timedelta(days=180)).strftime("%Y%m%d %H:%M:%S")

        fx = Contract()
        fx.secType = "CASH"
        fx.symbol = "USD"
        fx.currency = "JPY"
        fx.exchange = "IDEALPRO"

        #6 request data, using fx since I don't have Japanese data
        app.reqHistoricalData(4102, fx, queryTime, "1 M", "1 day", "MIDPOINT",
                              1, 1, False, [])


app = EClient(MyWrapper())  #1 create wrapper subclass and pass it to EClient
app.connect("127.0.0.1", 7497, clientId=123)  #2 connect to TWS/IBG
app.run()  #3 start message thread
Esempio n. 17
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ibapi.client import EClient
from ibapi.wrapper import EWrapper

app = EClient(EWrapper())
app.connect("127.0.0.1", 7497, clientId=0)
print("serverVersion:%s connectionTime:%s" %
      (app.serverVersion(), app.twsConnectionTime()))
if __name__ == '__main__':
    pass