开云体育

ctrl + shift + ? for shortcuts
© 2025 开云体育
Date

TWS alerts to API

 

Hi.

Can't find a way to get Alerts set up in TWS to show in API.
Or a way to set up Alert via API.
API documentation doesn't help.

Regards
Priit


IBAPI - Contract details for micro contracts MYM

 

Hello,

I'm new at this, and would like some help with Contract Definitions for the ECBOT exchange contracts.

Using the provided Python sample Program.py and am able to obtain snapshot data for GLOBEX and NYMEX, however with ECBOT I am not able to obtain any snapshot information unless I provide a conId, as per the contract definition:

contract = Contract()
contract.conId = 428519925
contract.secType = "FUT"
contract.exchange = "ECBOT"
contract.currency = "USD"
contract.localSymbol = "MYMM1"

However when the conId is omitted, as I do in all other contracts, I receive the dreaded 200 error message.
ERROR 1005 200 No security definition has been found for the request.

Is someone able to help me with the correct way of defining these contracts: MYM, YC, YK and YW?

Thanks,
KH


Re: ibapi nextValidId not always invoked

 

indeed, that is the solution i adopted too.
thank you very much @ScottBrian


Re: ibapi nextValidId not always invoked

 

thank you @ScottBrian,
this is indeed my first time to deal with threads.
my program is not intended to stop receiving data, but to handle as much of it.

about your solution:
i see the run() method of EReader is abruptly ending when the connection falls,
thus i think it may not snatch responses post disconnection.
to my satisfaction, data isn't being lost, as client.reader is pushing it's input to client.msg_queue, q that survives disconnection.

a friend (also brian) suggested on stackoverflow to join and stop after disconnection the data consumption loop, the EClient.run().
without very specific explanation, this solution actually works.
probably, some later handling of the messages in the queue, does need the now closed connection.

here is the working code. i'd like to set the syntax highlighting too:

?
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import MarketDataTypeEnum
from ibapi.errors import *
?
connection_errors = (
CONNECT_FAIL, UPDATE_TWS, NOT_CONNECTED, UNKNOWN_ID, UNSUPPORTED_VERSION,?
#BAD_LENGTH, BAD_MESSAGE,?
SOCKET_EXCEPTION, FAIL_CREATE_SOCK, SSL_FAIL,?
)
connection_error_codes = [error.code() for error in connection_errors]
?
?
import threading
import time
import logging
?
?
class IBapi(EWrapper, EClient):
?
nextorderId = None
ka_interval = None
?
clientid = None
hostname = None
portno = None
?
MarketDataType = None
onConnected = None
?
def __init__(
self, clientid, hostname='127.0.0.1', portno=7497,?
MarketDataType=None, onConnected=None, ka_interval=3):
?
self.clientid = clientid
self.hostname = hostname
self.portno = portno
self.ka_interval = ka_interval
?
EClient.__init__(self, self)
?
self.onConnected = onConnected
self.MarketDataType = MarketDataType or MarketDataTypeEnum.DELAYED
?
self.host_connect()
?
# Initialise the threads for various components
self._thread_ka = threading.Thread(target=self.keepAlive)
self._thread_ka.start()
?
def host_connect(self):
"""Connects to TWS with the appropriate connection parameters"""
if not self.hostname or not self.portno:
logging.error(f'hostname {self.hostname} or portno {self.portno} not [yet] defined')
return
super().connect(self.hostname, self.portno, self.clientid)
self._thread = threading.Thread(target=self.run)
self._thread.start()
?
def error(self, reqId, errorCode, errorString):
"""disconnect to handle communications errors"""
# clean the connection status
if errorCode in connection_error_codes and \
self.connState not in (EClient.CONNECTING,):
logging.error(
f'disconnect on connection_error {errorCode} "{errorString}"')
self.disconnect()
if hasattr(self, "_thread"):
self._thread.join(5)
time.sleep(5)
return super().error(reqId, errorCode, errorString)
?
def keepAlive(self):
data_lock = threading.Lock()
while self.ka_interval:
time.sleep(self.ka_interval)
connState = None
with data_lock:
connState = self.connState
isConnected = connState == EClient.CONNECTED
logging.error(f'is connected: {isConnected}')
if not isConnected:
isConnecting = connState == EClient.CONNECTING
if not isConnecting:
logging.error(f"let's connect")
self.host_connect()
else:
logging.error(f'already connecting')
else:
logging.error(f'requesting CurrentTime for keepAlive')
self.reqCurrentTime()
self.reqIds(1)
?
def host_connected(self):
self.reqMarketDataType(self.MarketDataType)
self.reqPositions()
?
def nextValidId(self, orderId):
print('====================================================')
logging.error(f'The next valid order id is: {orderId}')
print('====================================================')
super().nextValidId(orderId)
self.nextorderId = orderId
self.host_connected()
?
port_TWS_Live = 7496
port_IBGateway_Live = 4001
port_TWS_Simulated = 7497
port_IBGateway_Simulated = 4002
?
def main():
?
logging.basicConfig(
format='%(levelname)s:%(asctime)s:%(message)s', level=logging.WARN)
?
logging.info('Started')
?
app = IBapi(
1234,?
#portno=port_TWS_Live,?
portno=port_TWS_Simulated,?
)
?
logging.info('Finished')
?
if __name__ == '__main__':
main()
?


Re: ibapi nextValidId not always invoked

 

Hi Alex,
I have some additional thoughts:
IBapi __init__ calls host_connect which will be unsuccessful if TWS is not yet up. This we know. But then, __init__ instantiates a thread for the EClient run method and starts it. If the client in not yet connected, the EClient run method will see self.Isconnected as False and exit.
Later, keepAlive might get connected to TWS, but the EClient run thread is no longer active so we won't be seeing NextValidD get control (or anything else).

The quick fix is to instantiate a new run thread in keepAlive after the connect is successful. Also, I suggest that both run thread and keepAlive thread be made a part of the IBapi instance data so that they can be joined during shutdown.
Also, threads can not be restarted, so if they are made to be instance data, simply instantiate new threads as needed.

Cheers,
Scott


Re: OCA Order Examples

 

My apologies for the spamming of messages - last one.

I figured it out. For anyone else that searches for and finds this, my mistake was believing that I needed to submit the multiple orders through the one placeOrder. Separating them into 3 placeOrders (and fixing the orderId field) has now worked.


Re: OCA Order Examples

 

The ocaContract list above was just testing to see if I could use a list for that purpose - I obviously couldn't.


Re: OCA Order Examples

 

After working on this further, my main issue seems to be with the contract field in the placeOrder for the OCA. When checking via relevant prints, the list doesn't seem to contain the full contract details. Relevant code pasted below.

? ? ? ? ocaContract = [stock1contract, stock2contract, stock3contract]
? ? ? ? ocaOrders = [stock1limitorder, stock2limitorder, stock3limitorder]
? ? ? ? OneCancelsAll("TestOCA_", ocaOrders, 2)? ? ??
? ? ? ? for o in ocaOrders:
? ? ? ? ? ? self.placeOrder(orderId, Contract(), o)? ??
? ? ? ? ? ??print(Contract(), Order())
? ? ? ? ? ? print("printing o: ", o)



def OneCancelsAll(ocaGroup, ocaOrders, ocaType):
? ? for o in ocaOrders:
? ? ? ? o.ocaGroup = ocaGroup
? ? ? ? o.ocaType = ocaType
?
? ? return ocaOrders



Re: Do I need to create a GUI for using the IBAPI sample program TestCppClient. Thanks.

 

Thank you for your info, hymagik.
My MFC Dialog-based window program is running OK now.
Thank you anyway.


Re: ibapi nextValidId not always invoked

 

Hi Alex,
I had a similar problem with a connect being done on the heals of a disconnect. I determined that the EClient disconnect code failed to wait for the reader thread to come home. It was orphaned but still active and snatched the handshaking responses during the following connect.
Not sure you have the same problem, but just in case, following is my disconnect code that overrides the EClient disconnect. Try that out if you want.
You can either comment out the logging code or get scottbrian-utils from PyPI and add "from scottbrian_utils.diag_msg import get_formatted_call_sequence" to your imports.
Note also that you will need the add "self.disconnect_lock = Lock()" in your __init__ method for your IBapi class and add "from threading import Lock" to your imports.?
Note also in my disconnect_from_ib that I join the run thread to wait for it to come home before exiting the disconnect process. Having both the reader thread and the run thread finished makes for a clean connect.

###########################################################################
# disconnect_from_ib
###########################################################################
def disconnect_from_ib(self) -> None:
"""Disconnect from ib."""
logger.info('calling EClient disconnect')

self.disconnect() # call our disconnect (overrides EClient)

logger.info('join run_thread to wait for it to come home')
self.run_thread.join()

logger.info('disconnect complete')

###########################################################################
# disconnect
###########################################################################
def disconnect(self) -> None:
"""Call this function to terminate the connections with TWS."""
# We would like to call EClient.disconnect, but it does not wait for
# the reader thread to come home which leads to problems if a connect
# is done immediately after the disconnect. The still running reader
# thread snatches the early handshaking messages and leaves the
# connect hanging. The following code is from client.py and is
# modified here to add the thread join to ensure the reader comes
# home before the disconnect returns.
# Note also the use of the disconnect lock to serialize the two known
# cases of disconnect being called from different threads (one from
# mainline through disconnect_from_ib in AlgoApp, and one from the
# EClient run method in the run thread.
call_seq = get_formatted_call_sequence()
logger.debug("%s entered disconnect", call_seq)
with self.disconnect_lock:
logger.debug("%s setting conn state", call_seq)
self.setConnState(EClient.DISCONNECTED)
if self.conn is not None:
logger.info("%s disconnecting", call_seq)
self.conn.disconnect()
self.wrapper.connectionClosed()
reader_id = id(self.reader)
my_id = get_ident()
my_native_id = get_native_id()
logger.debug('about to join reader id %d for self id %d to'
' wait for it to come home on thread %d %d',
reader_id, id(self), my_id, my_native_id)
self.reader.join()
logger.debug('reader id %d came home for id(self) %d '
'thread id %d %d',
reader_id,
id(self), my_id, my_native_id)
self.reset()


? ? ? ?


OCA Order Examples

 

Hey everyone,

I'm in the process of setting up the IB Api in Python and I am pulling my hair out trying to get a One Cancels All order setup correctly (i.e. without errors). I was wondering if anyone would be able to please share some example code from Python for me to better understand the layout? I have reviewed the TWS API github resources extensively, but whether I am just not advanced in Python enough to understand it I don't know. I'm looking to setup OCA orders comprising multiple stocks - so not the typical Bracket Order (comprising parent and stoploss & profit target) OCA that seems to be discussed most often.?

Place Orders are going through fine (so the connection and setup of the code are ok) and I'm comfortable with the general logic of Python, but I just cannot work out the format needed to code the OCA order.

Any help would be greatly appreciated.

Thanks


Re: Is it possible to open multiple connection through TWS API?

 

Well then you do this. Connecting with different client IDs will allow you to stream quotes with one client and download historical data with the other for example.


Re: How Market Data Farm is ON when the API Client is not connected itself?

Nick
 

The TWS display of market data farm has nothing to do with the api. It is telling you that TWS itself is connected to IB's data farm server.

You broke your code when you changed it so that you are not calling connect before using other api functions. Or you are connecting, then disconnecting, then trying to use another api function.

On 5/11/2021 3:20 AM, Tareq Naushad wrote:
Hello,
I face a strange problem today when tried to extend my code in TWS Stream. Instead of calling the connect() method in the function where the live stream is running, I create a separate method and call it when required. For some unknown reason, the TWS API connection is not established, but Market Data Farm is ON!


Re: Is it possible to open multiple connection through TWS API?

 

Hello, Despair, Thanks for your message. Actually, I am not interested to store Historical Data in the database. I want to pull historical data direct from IB and calculate the required indicators.


Re: Is it possible to open multiple connection through TWS API?

 

You can be connected to the API with several different client IDs simultaneously.

However you don't really need the API to calculate indicators.


Is it possible to open multiple connection through TWS API?

 

Hello,
In one of our custom web-based applications for strategy making in trading, we are running a TWS API connection to stream data (which is run all-time). Now we want to open another connection to calculate different indicators like ATR, RSI, except closing the previous connection. I mean: one TWS API connection will run for streaming data, and another (or probably more than one) connection will run for calculating different indicator values. Although we have no idea whether it is a best practice or not to run multiple connections, we want to know whether opening a new connection will impact the previously running connection? I mean if a new connection is open for indicator whether the connection of streaming will work or not.

Does anyone have any idea?

Thanks

Tareq


ibapi nextValidId not always invoked

 

i built a small ibapi python app to run some strategy, while taking care to stay connected to tws.

if tws is inactive, the python app will start and wait, and will connect to tws when tws will start, but here's my problem:

nextValidId won't be invoked

here is my code. i repeat, nextValidId will be invoked only while connected to a tws session that was active before my app connects.

as you can see, in a tws session that wasn't active before this script starts, nextValidId won't get invoked at all, not even manually by reqIds.


from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import MarketDataTypeEnum
from ibapi.errors import *

connection_errors = (
    CONNECT_FAIL, UPDATE_TWS, NOT_CONNECTED, UNKNOWN_ID, UNSUPPORTED_VERSION, 
    #BAD_LENGTH, BAD_MESSAGE, 
    SOCKET_EXCEPTION, FAIL_CREATE_SOCK, SSL_FAIL, 
)
connection_error_codes = [error.code() for error in connection_errors]


import threading
import time
import logging


class IBapi(EWrapper, EClient):

#   connection_lost = True

    clientid = None
    hostname = None
    portno = None
    onConnected = None

    MarketDataType = None

    def __init__(
            self, clientid, hostname='127.0.0.1', portno=7497, 
            MarketDataType=None, onConnected=None, ka_interval=3):

        self.clientid = clientid
        self.hostname = hostname
        self.portno = portno
        self.ka_interval = ka_interval

        EClient.__init__(self, self)

        self.onConnected = onConnected
        self.MarketDataType = MarketDataType or MarketDataTypeEnum.DELAYED

        self.host_connect()

        # Initialise the threads for various components
        thread = threading.Thread(target=self.run)
        thread.start()
        setattr(self, "_thread", thread)

        thread = threading.Thread(target=self.keepAlive)
        thread.start()
        setattr(self, "_thread_ka", thread)

    def host_connect(self):
        """Connects to TWS with the appropriate connection parameters"""
        if not self.hostname or not self.portno:
            logging.error(f'hostname {self.hostname} or portno {self.portno} not [yet] defined')
            return
        super().connect(self.hostname, self.portno, self.clientid)

    def error(self, reqId, errorCode, errorString):
        """disconnect to handle communications errors"""
        # clean the connection status
        if errorCode in connection_error_codes and \
                self.connState not in (EClient.CONNECTING,):
            logging.error(
                f'reset on connection_error {errorCode} "{errorString}"???')
#           self.connection_lost = True
            self.disconnect()
        return super().error(reqId, errorCode, errorString)

    def keepAlive(self):
        data_lock = threading.Lock()
        while self.ka_interval:
            time.sleep(self.ka_interval)
#           isConnected = self.isConnected()
            connState = None
            with data_lock:
                connState = self.connState
#               connection_lost = self.connection_lost
            isConnected = connState == EClient.CONNECTED
            logging.error(f'is connected: {isConnected}')
            if not isConnected:
                isConnecting = connState == EClient.CONNECTING
                if not isConnecting:
                    logging.error(f"let's connect")
                    self.host_connect()
                else:
                    logging.error(f'already connecting')
            else:
                logging.error(f'requesting CurrentTime for keepAlive')
#               if connection_lost:
#                   logging.error('reconnecting. should auto invoke nextValidId')
#                   self.reqIds(1)
#                   self.host_connected()
                self.reqCurrentTime()
                self.reqIds(1)

    def host_connected(self):
#       if self.connection_lost:
#           self.connection_lost = False
            self.reqMarketDataType(self.MarketDataType)
            self.reqPositions()

    def nextValidId(self, orderId):
        print('====================================================')
        logging.error(f'The next valid order id is: {orderId}')
        print('====================================================')
        super().nextValidId(orderId)
        self.nextorderId = orderId
        self.host_connected()

port_TWS_Live = 7496
port_IBGateway_Live = 4001
port_TWS_Simulated = 7497
port_IBGateway_Simulated = 4002

def main():
    logging.basicConfig(
        format='%(levelname)s:%(asctime)s:%(message)s', level=logging.WARN)
    logging.info('Started')

    logging.debug('This message should appear on the console')

    app = IBapi(
        1234, 
        #portno=port_TWS_Live, 
        portno=port_TWS_Simulated, 
    )

    logging.info('Finished')

if __name__ == '__main__':
    main()

i have also posted on?


Re: Contents of "SecIdList" within a contract object.

 

I doubt they'd have Ric or Sedol..? Those are also subscription based on the source side, which I haven't seen mentioned in IB..? I believe the SecIdList is populated with what's available regardless, and CUSIP is the only optional one subscription dependent.

As for support, calling is unlikely to be useful. The people who can answer these questions aren't ones you can call unless your account has 9+ digits in the balance.??

-Peter


Contents of "SecIdList" within a contract object.

Aquiles Páez
 

According to the TWS API guide, we have the following definition for this sub-field of the Contract object:

List<??>?
? A list of contract identifiers that the customer is allowed to view. CUSIP/ISIN/etc. For US stocks, receiving the ISIN requires the CUSIP market data subscription. For Bonds, the CUSIP or ISIN is input directly into the symbol field of the??class.

I have the CUSIP sub, so I can view the ISIN code for American Stocks. What if I wanted to see other ID's? Like RIC, CUSIP, SEDOL? I remember seeing them listed in the field of SecIdType when one specifies the contract.?

Which subscriptions would allow me to get that? Does anyone know? Lately it has been extremely difficult to get attended through the TOLL FREE number's Customer Support line of IB, I'd ask them directly but I think I prefer coming through here first.?


Historic ETF NAV

 

Hello,
Is there a way to get daily historic ETF NAV?, i.e. the NAV Prior Close value as shown in ETF watch list columns here:


Thanks