Search code examples
pythonapiattributeerrorinteractive-brokers

AttributeError: 'NoneType' object has no attribute 'conId'


I am using the Interactive brokers python api to make a limit order of AMD. So far the code for that is:

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.order import Order
import threading
import time


class TradingApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
 
    
    def nextValidId(self, orderId):
        self.nextValidId = orderId

def websocket_con():
    app.run()
    
        
app = TradingApp()
app.connect("127.0.0.1", 7497, clientId=13)

con_thread = threading.Thread(target=websocket_con, daemon=True)
con_thread.start()
time.sleep(1)

def USstock(symbol, secType='STK', Currency='USD', exchnange = 'SMART'):
    contract=Contract()
    contract.symbol = symbol
    contract.secType = secType
    contract.currency = Currency
    contract.exchange = exchnange

def limit_order(direction, quantity, price):
    order=Order()
    order.action = direction
    order.orderType = 'LMT'
    order.totalQuantity = quantity
    order.lmtPrice = price
order_id = app.nextValidId
app.placeOrder(order_id,USstock('AMD'),limit_order('BUY',10,50))

Though as I am running it I am getting the error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-49-407bad8e9645> in <module>
     40     order.lmtPrice = price
     41 order_id = app.nextValidId
---> 42 app.placeOrder(order_id,USstock('AMD'),limit_order('BUY',10,50))

~\AppData\Roaming\Python\Python37\site-packages\ibapi-9.76.1-py3.7.egg\ibapi\client.py in placeOrder(self, orderId, contract, order)
   1041         # send contract fields
   1042         if self.serverVersion() >= MIN_SERVER_VER_PLACE_ORDER_CONID:
-> 1043             flds.append(make_field( contract.conId))
   1044         flds += [make_field( contract.symbol),
   1045             make_field( contract.secType),

AttributeError: 'NoneType' object has no attribute 'conId'

But I dont know where I have used 'conId' or why this error is showing. Any ideas? Thanks!


Solution

  • The issue is that at the end of the both functions, I should have added to return the contract and the order because if not all I am doing is just deffing the components in the function. So the code should be:

    def Contract_Order():
        contract=Contract()
        contract.symbol = 'AMD'
        contract.secType = 'STK'
        contract.currency = 'USD'
        contract.exchange = 'ISLAND'
        return contract
    
    def Limit_Order():
        order=Order()
        order.action = 'BUY'
        order.orderType = 'LMT'
        order.totalQuantity = 10
        order.lmtPrice = 100
        return order
    

    Simply fixing this by adding return contract and return order