简体   繁体   中英

Ibpy with Interactive Brokers API not working

I feel there is something fundamentally wrong. I go from example code to example code trying each out and I have never had any success.

Below is a collection of scripts Ive run and the response. Most of these scripts come from example found here on StackOverflow for which the person seems to have success with (after some help). Alas I have no success and just feel there must be something really wrong with what Im doing.

Before I start with the scripts that dont seem to work here are my configs for Interactive brokers GUI, TWS.

API - Settings

checked: Enable ActiveX and Socket Clients. unchecked: Enable DDE clients. unchecked: Read-Only API. checked: Download open orders on connection. checked: Include FX posistions when sending portfolio. checked: Send status updates for EEP. Socket port = 7496. checked: Use negative numbers to bind automatic orders. unchecked: Create API message log file. unchecked: Include market data in API log file. unchecked: Let API account requests switch user-visable acc subscription. Logging Level = Error. Master API client ID = 100. Timeout to send bulk data to API is 30 seconds. Component Exch Separator = Blank (no entry here). checked: Allow connections from localhost only.

API - Precautions checked: Bypass Order Precautions for API Orders. everything else all unchecked in this tab.

Example 1.

#test_conn.py

from ib.opt import ibConnection
con = ibConnection(port=7496,clientId=100)
print(con.connect())

Running script and response

C:\Users\alex>python test_conn.py
Server Version: 76
TWS Time at connection:20160314 16:13:59 ICT
True
True

I think I can make a connection to TWS then?

Example 2.

#test_portfolio.py

from ib.opt import ibConnection, message

def acct_update(msg):
    print(msg)

con = ibConnection(port=7496,clientId=100)
con.register(acct_update,
             message.updateAccountValue,
             message.updateAccountTime,
             message.updatePortfolio)
con.connect()
con.reqAccountUpdates(True,'DU358588')

#don't forget to disconnect somehow when done
con.disconnect()

Running script and response

C:\Users\alex>python test_portfolio.py
Server Version: 76
TWS Time at connection:20160314 16:25:59 ICT

C:\Users\alex>

So nothing gets returned?

Example 3.

#test_mkt_data.py

from ib.opt import ibConnection, message
from ib.ext.Contract import Contract
from time import sleep

def my_callback_handler(msg):
    inside_mkt_bid = ''
    inside_mkt_ask = ''

    if msg.field == 1:
        inside_mkt_bid = msg.price
        print 'bid', inside_mkt_bid
    elif msg.field == 2:
        inside_mkt_ask = msg.price
        print 'ask', inside_mkt_ask

tws = ibConnection()
tws.register(my_callback_handler, message.tickSize, message.tickPrice)
tws.connect()

c = Contract()
c.m_symbol = "GOOG"
c.m_secType = "STK"
c.m_exchange = "SMART"
c.m_currency = "USD"

tws.reqMktData(1,c,"",False)
sleep(25)

print 'All done'

tws.disconnect()

Running script and response

C:\Users\alex>python test_mkt_data.py
Server Version: 76
TWS Time at connection:20160314 16:31:54 ICT
All done
Exception in thread EReader (likely raised during interpreter shutdown):
C:\Users\alex>

Again, nothing gets returned?

Example 4.

#test_historical.py

from time import sleep, strftime
from time import sleep
from ib.ext.Contract import Contract
from ib.opt import ibConnection, message

def my_account_handler(msg):
    print(msg)

def my_tick_handler(msg):
    print(msg)

def my_hist_data_handler(msg):
    print(msg)


if __name__ == '__main__':

    con = ibConnection(port=7496,clientId=100)
    con.register(my_account_handler, 'UpdateAccountValue')
    con.register(my_tick_handler, message.tickSize, message.tickPrice)
    con.register(my_hist_data_handler, message.historicalData)
    con.connect()

    print(con.isConnected())

    def inner():

        qqqq = Contract()
        qqqq.m_secType = "STK" 
        qqqq.m_symbol = "GOOG"
        qqqq.m_currency = "USD"
        qqqq.m_exchange = "SMART"
        endtime = strftime('%Y%m%d %H:%M:%S')
    print(endtime)
        print(con.reqHistoricalData(1,qqqq,endtime,"5 D","1     hour","MIDPOINT",0,1))



        sleep(10)

    inner()
    sleep(5)
    print('disconnected', con.disconnect())
    print(con.isConnected())

Running script and response

C:\Users\alex>python test_historical.py
Server Version: 76
TWS Time at connection:20160314 16:38:03 ICT
True
20160314 16:38:04
None
('disconnected', True)
False

C:\Users\alex>

There is no historical data? Take away the "print" in "print(con.req..." still make no difference.

Example 5.

# ib_api_demo.py

from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message

def error_handler(msg):
    """Handles the capturing of error messages"""
    print "Server Error: %s" % msg

def reply_handler(msg):
    """Handles of server replies"""
    print "Server Response: %s, %s" % (msg.typeName, msg)

def create_contract(symbol, sec_type, exch, prim_exch, curr):
    """Create a Contract object defining what will
    be purchased, at which exchange and in which currency.

    symbol - The ticker symbol for the contract
    sec_type - The security type for the contract ('STK' is 'stock')
    exch - The exchange to carry out the contract on
    prim_exch - The primary exchange to carry out the contract on
    curr - The currency in which to purchase the contract"""
    contract = Contract()
    contract.m_symbol = symbol
    contract.m_secType = sec_type
    contract.m_exchange = exch
    contract.m_primaryExch = prim_exch
    contract.m_currency = curr
    return contract

def create_order(order_type, quantity, action):
    """Create an Order object (Market/Limit) to go long/short.

    order_type - 'MKT', 'LMT' for Market or Limit orders
    quantity - Integral number of assets to order
    action - 'BUY' or 'SELL'"""
    order = Order()
    order.m_orderType = order_type
    order.m_totalQuantity = quantity
    order.m_action = action
    return order

if __name__ == "__main__":
    # Connect to the Trader Workstation (TWS) running on the
    # usual port of 7496, with a clientId of 100
    # (The clientId is chosen by us and we will need 
    # separate IDs for both the execution connection and
    # market data connection)
    tws_conn = Connection.create(port=7496, clientId=100)
    tws_conn.connect()

    # Assign the error handling function defined above
    # to the TWS connection
    tws_conn.register(error_handler, 'Error')

    # Assign all of the server reply messages to the
    # reply_handler function defined above
    tws_conn.registerAll(reply_handler)

    # Create an order ID which is 'global' for this session. This
    # will need incrementing once new orders are submitted.
    order_id = 1

    # Create a contract in a stock via SMART order routing
    goog_contract = create_contract('BHP', 'STK', 'SMART', 'SMART', 'AUD')

    # Go long 100 shares of Google
    goog_order = create_order('MKT', 100, 'BUY')

    # Use the connection to the send the order to IB
    tws_conn.placeOrder(order_id, goog_contract, goog_order)

    # Disconnect from TWS
    tws_conn.disconnect()

running and response

C:\Users\alex>python ib_api_demo.py
Server Version: 76
TWS Time at connection:20160314 16:43:55 ICT
Server Error: <error id=-1, errorCode=2104, errorMsg=Market data farm connection is OK:afarm>

Server Response: error, <error id=-1, errorCode=2104, errorMsg=Market data farm connection is OK:afarm>
C:\Users\alex>

So nothing seems to work and I feel like there is just something fundamental I have missed? I have got TWS logged in and running when I run the python scripts and the TWS API settings (see above) seem correct in regards to what everyone else is saying online.

Any help much appreciated.

I tried the codes you provided.

Example 2. Add sleep(1) before con.disconnect()

Example 3. tws = ibConnection() should be changed to tws = ibConnection(port=7496,clientId=100)

Example 4, "1 hour"--> too many spaces, leave only one space and delete extra ones.

Example 5. Be careful with the next valid order id. It should be greater than the order id in Ib system. you may use the following code to get the next valid order id from system.:

def save_order_id(msg):

    print('Next Valid ID is ' + str(msg.orderId))

con = ibConnection(port=7496,clientId=100)

con.register(save_order_id, 'NextValidId')

con.connect()

sleep(1)

con.disconnect()

You are good to go with the above changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM