开云体育

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

Submit orders to TWS via API


 

Hi ,
I am attempting to use the piece of code (see below) to place orders to TWS.? ?it works fine executing the orders on the demo account with confirmation?from TWS as expected...? However when connected to live mode it does not execute successfully although connection to?TWS is confirmed..? The objective is to have this code running?continuously in the background executing trade files from a trade folder....

Not a python expert so excuse minor details!..? just concentrating on getting this to work in the live mode

Any help appreciated..? thanks

regards
ed


# ib_api_demo.py####

from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message
import sys
import time
import os
import os.path
import shutil
import _winapi
? ?

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 nextValid(self, orderId):
? ? self.nextOrderId=orderId
? ? self.start()

def create_contract(symbol, sec_type, exch, prim_exch, curr):
? ? 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

def GetFileDetails():
? ? myList = []
? ? global my_path
? ? my_path = os.path.join('C:\\',
? ? ? ? ? ? ? ? ? ? ? trade_path,
? ? ? ? ? ? ? ? ? ? ? ? 'trade.txt')

? ? with open(my_path , "r") as file:
? ? ? ? first_line = file.readline()
? ?
? ? print(first_line)
? ? myList=first_line.split(',')
? ? return myList


? ?
? ? ? ?
contract_detail=[]
a=1


while True:
#if __name__ == "__main__":
? ? try:
? ? ? ? # Connect to the Trader Workstation (TWS) running on the
? ? ? ? # usual port of 7496, with a clientId of 100
? ? ? ? tws_conn = Connection.create(port=7496, clientId=100)
? ? ? ? tws_conn.connect()
? ? ? ? print ("connected!" + "\n")

? ? ? ? # 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)

? ? ? ? contract_detail=GetFileDetails()


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

? ? ? ? # Create a contract in stock via SMART order routing
? ? ? ? eur_contract= create_contract(contract_detail[1], contract_detail[2], contract_detail[3], contract_detail[4], contract_detail[5])

? ? ? ? # Go long 100 shares of Google
? ? ? ? #aapl_order = create_order('MKT', 10, 'BUY')
? ? ? ? eur_order = create_order(contract_detail[6], contract_detail[7], contract_detail[8])

? ? ? ? # Use the connection to the send the order to IB
? ? ? ? tws_conn.placeOrder(order_id, eur_contract, eur_order)
? ? ? ?

? ? ? ? # Disconnect from TWS ? ? ? ? ? ? ? ? ?
? ? ? ? tws_conn.disconnect()

? ? ? ? print ("execution complete")

? ? ? ? os.rename(r'trade_folder\trade.txt',r'traded_folder\traded.txt')
? ? ? ? time.sleep(0.5)

? ? ? ?
? ?
? ? except: # catch *all* exceptions
? ? ? ? #e = sys.exc_info()[0]
? ? ? ? #print( "<p>Error: %s</p>" % e )
? ? ? ? print (file=sys.stderr)



? ? time.sleep(5)
? ? os.execv(sys.executable, ['python'] + sys.argv) #re-execute script!!!




? ??


 

开云体育

The basic things that I would check are:

?

Usually TWS has one port for paper (7497) and a different port for live (7496).

?

Also, in IB Gateway you have to set the account options to allow login and non-read-only access separately.

?

Nich

?

From: [email protected] <[email protected]> On Behalf Of Ed Bell via groups.io
Sent: 05 May 2021 18:09
To: [email protected]
Subject: [TWS API] Submit orders to TWS via API

?

Hi ,

I am attempting to use the piece of code (see below) to place orders to TWS.? ?it works fine executing the orders on the demo account with confirmation?from TWS as expected...? However when connected to live mode it does not execute successfully although connection to?TWS is confirmed..? The objective is to have this code running?continuously in the background executing trade files from a trade folder....

?

Not a python expert so excuse minor details!..? just concentrating on getting this to work in the live mode

?

Any help appreciated..? thanks

?

regards

ed

?

?

# ib_api_demo.py####

from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message
import sys
import time
import os
import os.path
import shutil
import _winapi
? ?

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 nextValid(self, orderId):
? ? self.nextOrderId=orderId
? ? self.start()

def create_contract(symbol, sec_type, exch, prim_exch, curr):
? ? 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

def GetFileDetails():
? ? myList = []
? ? global my_path
? ? my_path = os.path.join('C:\\',
? ? ? ? ? ? ? ? ? ? ? trade_path,
? ? ? ? ? ? ? ? ? ? ? ? 'trade.txt')

? ? with open(my_path , "r") as file:
? ? ? ? first_line = file.readline()
? ?
? ? print(first_line)
? ? myList=first_line.split(',')
? ? return myList


? ?
? ? ? ?
contract_detail=[]
a=1


while True:
#if __name__ == "__main__":
? ? try:
? ? ? ? # Connect to the Trader Workstation (TWS) running on the
? ? ? ? # usual port of 7496, with a clientId of 100
? ? ? ? tws_conn = Connection.create(port=7496, clientId=100)
? ? ? ? tws_conn.connect()
? ? ? ? print ("connected!" + "\n")

? ? ? ? # 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)

? ? ? ? contract_detail=GetFileDetails()


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

? ? ? ? # Create a contract in stock via SMART order routing
? ? ? ? eur_contract= create_contract(contract_detail[1], contract_detail[2], contract_detail[3], contract_detail[4], contract_detail[5])

? ? ? ? # Go long 100 shares of Google
? ? ? ? #aapl_order = create_order('MKT', 10, 'BUY')
? ? ? ? eur_order = create_order(contract_detail[6], contract_detail[7], contract_detail[8])

? ? ? ? # Use the connection to the send the order to IB
? ? ? ? tws_conn.placeOrder(order_id, eur_contract, eur_order)
? ? ? ?

? ? ? ? # Disconnect from TWS ? ? ? ? ? ? ? ? ?
? ? ? ? tws_conn.disconnect()

? ? ? ? print ("execution complete")

? ? ? ? os.rename(r'trade_folder\trade.txt',r'traded_folder\traded.txt')
? ? ? ? time.sleep(0.5)

? ? ? ?
? ?
? ? except: # catch *all* exceptions
? ? ? ? #e = sys.exc_info()[0]
? ? ? ? #print( "<p>Error: %s</p>" % e )
? ? ? ? print (file=sys.stderr)



? ? time.sleep(5)
? ? os.execv(sys.executable, ['python'] + sys.argv) #re-execute script!!!




? ??


 

Nich

Thanks for your reply...??
i am using the correct port for the live environment...? ?I am able to connect in live mode but it appears that order placed not getting confirmed in live like in demo! mode...i am connecting via TWS so was not?aware that i also needed to configure?the IB gateway but will give that a try too

regards
Ed


On Wed, May 5, 2021 at 6:13 PM Nich Overend <nich@...> wrote:

The basic things that I would check are:

?

Usually TWS has one port for paper (7497) and a different port for live (7496).

?

Also, in IB Gateway you have to set the account options to allow login and non-read-only access separately.

?

Nich

?

From: [email protected] <[email protected]> On Behalf Of Ed Bell via
Sent: 05 May 2021 18:09
To: [email protected]
Subject: [TWS API] Submit orders to TWS via API

?

Hi ,

I am attempting to use the piece of code (see below) to place orders to TWS.? ?it works fine executing the orders on the demo account with confirmation?from TWS as expected...? However when connected to live mode it does not execute successfully although connection to?TWS is confirmed..? The objective is to have this code running?continuously in the background executing trade files from a trade folder....

?

Not a python expert so excuse minor details!..? just concentrating on getting this to work in the live mode

?

Any help appreciated..? thanks

?

regards

ed

?

?

# ib_api_demo.py####

from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message
import sys
import time
import os
import os.path
import shutil
import _winapi
? ?

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 nextValid(self, orderId):
? ? self.nextOrderId=orderId
? ? self.start()

def create_contract(symbol, sec_type, exch, prim_exch, curr):
? ? 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

def GetFileDetails():
? ? myList = []
? ? global my_path
? ? my_path = os.path.join('C:\\',
? ? ? ? ? ? ? ? ? ? ? trade_path,
? ? ? ? ? ? ? ? ? ? ? ? 'trade.txt')

? ? with open(my_path , "r") as file:
? ? ? ? first_line = file.readline()
? ?
? ? print(first_line)
? ? myList=first_line.split(',')
? ? return myList


? ?
? ? ? ?
contract_detail=[]
a=1


while True:
#if __name__ == "__main__":
? ? try:
? ? ? ? # Connect to the Trader Workstation (TWS) running on the
? ? ? ? # usual port of 7496, with a clientId of 100
? ? ? ? tws_conn = Connection.create(port=7496, clientId=100)
? ? ? ? tws_conn.connect()
? ? ? ? print ("connected!" + "\n")

? ? ? ? # 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)

? ? ? ? contract_detail=GetFileDetails()


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

? ? ? ? # Create a contract in stock via SMART order routing
? ? ? ? eur_contract= create_contract(contract_detail[1], contract_detail[2], contract_detail[3], contract_detail[4], contract_detail[5])

? ? ? ? # Go long 100 shares of Google
? ? ? ? #aapl_order = create_order('MKT', 10, 'BUY')
? ? ? ? eur_order = create_order(contract_detail[6], contract_detail[7], contract_detail[8])

? ? ? ? # Use the connection to the send the order to IB
? ? ? ? tws_conn.placeOrder(order_id, eur_contract, eur_order)
? ? ? ?

? ? ? ? # Disconnect from TWS ? ? ? ? ? ? ? ? ?
? ? ? ? tws_conn.disconnect()

? ? ? ? print ("execution complete")

? ? ? ? os.rename(r'trade_folder\trade.txt',r'traded_folder\traded.txt')
? ? ? ? time.sleep(0.5)

? ? ? ?
? ?
? ? except: # catch *all* exceptions
? ? ? ? #e = sys.exc_info()[0]
? ? ? ? #print( "<p>Error: %s</p>" % e )
? ? ? ? print (file=sys.stderr)



? ? time.sleep(5)
? ? os.execv(sys.executable, ['python'] + sys.argv) #re-execute script!!!




? ??


 

Hi Ed,
Just a wild guess - check to ensure the "Read-Only API" setting in the TWS API Settings dialog is NOT checked.

Cheers,
Scott


 

Hi Scott

Thanks for reply..? Read-Only box is unchecked?

I need to mention that when i run the version of the program which is single execution it works...? ?however the version i shared which runs in a continuous loop does not work


regards
Ed



On Wed, May 5, 2021 at 11:25 PM <sbtuttle@...> wrote:
Hi Ed,
Just a wild guess - check to ensure the "Read-Only API" setting in the TWS API Settings dialog is NOT checked.

Cheers,
Scott


 

Ed,

Here is the key line from you:

"However when connected to live mode it does not execute successfully"

If you detail what you mean by "successfully" your problem will be solved. This is a general term. You didn't say if you are getting an error OR not. And if Yes, what is the error?

If you are not getting an error in your callback, check API logs in TWS.

If this works in demo, it should work in love too.

Mostly, this issue comes back to IDs. Reset ID in TWS helps.

Also, sometimes you need to turn API settings OFF and ON for connection. Maybe it misbehaves with binding to ports.

- Bruce


On Wed, May 5, 2021, 7:19 PM Ed Bell <ed.ebell@...> wrote:
Hi Scott

Thanks for reply..? Read-Only box is unchecked?

I need to mention that when i run the version of the program which is single execution it works...? ?however the version i shared which runs in a continuous loop does not work


regards
Ed



On Wed, May 5, 2021 at 11:25 PM <sbtuttle@...> wrote:
Hi Ed,
Just a wild guess - check to ensure the "Read-Only API" setting in the TWS API Settings dialog is NOT checked.

Cheers,
Scott


 

Hi Bruce,

many thanks for your reply

please see response?inline

On Thu, May 6, 2021 at 1:30 AM Bruce B <bruceb444@...> wrote:
Ed,

Here is the key line from you:

"However when connected to live mode it does not execute successfully"?

If you detail what you mean by "successfully" your problem will be solved. This is a general term. You didn't say if you are getting an error OR not. And if Yes, what is the error?
>>>I am connected to TWS and get a confirmation message... but when the order is placed there is no confirmation from TWS of success or failure...? ?no messages....but will check logs as suggested
i am also catching all exception with following code..? ?this may be preventing any messages from tws... will check again
?except: # catch *all* exceptions
? ? ? ? #e = sys.exc_info()[0]
? ? ? ? #print( "<p>Error: %s</p>" % e )
? ? ? ? print (file=sys.stderr)?



If you are not getting an error in your callback, check API logs in TWS.
>>>will do
?

If this works in demo, it should work in love too.
>>>i agree...? and the single execution version works live as well... however that is not useful for me as i need the program to run independently in the background
?

Mostly, this issue comes back to IDs. Reset ID in TWS helps.
>>>?i did reset the ID to 1...? ?the latest ID is always captured before order is placed... which removes the potential for that issue?

Also, sometimes you need to turn API settings OFF and ON for connection. Maybe it misbehaves with binding to ports.
>>>not sure what you mean by turning API settings off/on...pls explain

Thanks again
Ed

?
- Bruce

On Wed, May 5, 2021, 7:19 PM Ed Bell <ed.ebell@...> wrote:
Hi Scott

Thanks for reply..? Read-Only box is unchecked?

I need to mention that when i run the version of the program which is single execution it works...? ?however the version i shared which runs in a continuous loop does not work


regards
Ed



On Wed, May 5, 2021 at 11:25 PM <sbtuttle@...> wrote:
Hi Ed,
Just a wild guess - check to ensure the "Read-Only API" setting in the TWS API Settings dialog is NOT checked.

Cheers,
Scott


 

On Wed, May 5, 2021 at 08:08 PM, Ed Bell wrote:
# Disconnect from TWS ? ? ? ? ? ? ? ? ?
? ? ? ? tws_conn.disconnect()

two cents from my side, consider these steps:

1. bringing TWS connect disconnect outside of infinite loop

2. implement filesystem watchdog observer, for example:??

3. implement openOrder / orderStatus callbacks:??

as of now, your code disconnects from TWS immediately upon placing order, without waiting callbacks from TWS.

Artyom


 

Hi Artyom

Thanks for your reply...? ?

Suggestion (1) resolved the issue

thanks all..? for your inputs

regards
ed


On Thu, May 6, 2021 at 10:03 AM Artyom T. <artyom.tyazhelov@...> wrote:
On Wed, May 5, 2021 at 08:08 PM, Ed Bell wrote:
# Disconnect from TWS ? ? ? ? ? ? ? ? ?
? ? ? ? tws_conn.disconnect()

two cents from my side, consider these steps:

1. bringing TWS connect disconnect outside of infinite loop

2. implement filesystem watchdog observer, for example:??

3. implement openOrder / orderStatus callbacks:??

as of now, your code disconnects from TWS immediately upon placing order, without waiting callbacks from TWS.

Artyom