Beispiel #1
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 #2
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 #3
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 #4
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 #5
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()
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
    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
Beispiel #8
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 #9
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 #10
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 #11
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 #12
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 #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()
Beispiel #14
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 #15
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 #16
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 #17
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
    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 #19
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 #20
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 #21
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
Beispiel #22
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 #23
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 #24
0
    def __init__(self, addr, port, client_id):
        EWrapper.__init__(self)
        EClient.__init__(self, self)
        self.candle_data = []  #Initialize variable to store candle stick data

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

        # Launch the client thread
        thread = threading.Thread(target=self.run)
        thread.start()
Beispiel #25
0
 def __init__(self, contractlist, filepath):
     EWrapper.__init__(self)
     iclient.__init__(self, wrapper=self)
     self.filepath = filepath
     self.quotedatadict = {}
     self.reqID_contract_dict = {}
     n = 0
     for c in contractlist:
         n += 1
         self.reqID_contract_dict[n] = c
     self.refresher = threading.Timer(10, self.refreshfun)
Beispiel #26
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)
Beispiel #27
0
 def __init__(self, timeout: int = None):
     """
     Create an EWrapper to provide blocking access to the callback-based IB API.
     :param timeout: Amount of time in seconds to wait for a response before giving up. Use None to never give up.
     """
     EWrapper.__init__(self)
     self.timeout = timeout
     self._app = None
     self.connected = Event()
     self.pending_responses = {}
     self.next_request_id = 0
     self.thread = None
Beispiel #28
0
    def __init__(self):
        EWrapper.__init__(self)
        self.is_connected = False

        # Stores the complete contract attributes of the contracts returned by a market scan
        self.contracts = []
        # Stores the fundamental ratios returned by a streaming market data subscription
        self.fundamentals = []
        # Stores the price volume data returned by IB
        self.pv_bars = []
        # Indicates whether or not all of the data for the current IB historical data request has been returned
        self.historical_data_returned = False
 def __init__(self):
     EWrapper.__init__(self)
     EClient.__init__(self, wrapper=self)
     #self.df = pd.DataFrame(columns=['reqid', 'Position', 'Operation', 'Side', 'Price', 'Size', 'Time'])
     # ! [socket_init]
     self.nKeybInt = 0
     self.started = False
     self.nextValidOrderId = None
     self.permId2ord = {}
     self.globalCancelOnly = False
     self.simplePlaceOid = None
     self._my_errors = {}
    def __init__(self, addr, port, client_id):
        EWrapper.__init__(self)
        EClient.__init__(self, self)
        self.contracts = []
        self.conids = []
        self.symbols = []

        # Connect to TWS
        self.connect(addr, port, client_id)
        self.count = 0

        # Launch the client thread
        thread = threading.Thread(target=self.run)
        thread.start()