¿ªÔÆÌåÓý

ctrl + shift + ? for shortcuts
© 2025 Groups.io
Date

Sell order for Options not going through in Paper trading mode

 

HI i tried a buy order followed by a sell order for TSLA/SPX options.
THe buy order goes through in about few seconds - the order gets fulfilled and the program also gets a call back ( with orderStatus as fulfilled.)
But the sell order dont go through. I am able to see the order in TWS window , but it doesn't get fullfilled for a very long time and on market close the order get cancelled.??
Anyone face similar issues??
Pasting my sample code? for Sell (? Buy Call is also almost exactly same )?

contract.symbol("SPX");
contract.secType("OPT");
contract.right("P");
contract.lastTradeDateOrContractMonth("220901");
contract.strike(4190.00);
//Get contract details?
contract = getContractDetails(contract);? // this basically calls m_client.reqContractDetails()

//Create new order?
Order order = new Order();
order.orderId(orderId);
order.action(Types.Action.SELL);
order.orderType(OrderType.MKT);
order.totalQuantity(1);
?
//Place order
m_client.placeOrder(orderId,contract,order);


Re: check if running in Paper or Live trading mode programatically

 

thanks alot . worked :)?


Re: order quantity gets systematically set to 1

 

Ok, so I found the answer, sharing for information.
It was a simple casting from a floating quantity number that the API didn't like.

I had to use?order.totalQuantity = round(quantity)?as the API is expecting an integer there; that's it.


Re: suggestions for simple GUI : IBAPI - python - windows

Erez Kaplan
 

Hi Steve,

THANKS, that's exactly what I was looking for.
Will check it and report results.

Cheers, Erez


order quantity gets systematically set to 1

 

Hello, not sure what I am doing wrong here, just generating limit orders similarly to the IB example, but the quantity gets set to 1.. why?
Contract is vanilla FX CASH pairs.

def generate_limit_order(action: str, quantity: float, limitPrice: float):
print(f'{quantity=}') # prints quantity=163233.980189104
order = Order()
order.action = action
order.orderType = "LMT"
order.totalQuantity = quantity
print(f'{order.totalQuantity=}') # prints order.totalQuantity=163233.980189104
order.lmtPrice = limitPrice
return order
then

api.placeOrder(orderId, strategy.target.contract, order)
Run:
Order Message:
BUY 1 AUD.NZD Forex
Warning: Your order size is below the AUD 25000 IdealPro minimum and will be routed as an odd lot order.


Re: US market Index contact name

 

¿ªÔÆÌåÓý

Thank you so much for the info ?


From: [email protected] <[email protected]> on behalf of hymagik via groups.io <hymagik@...>
Sent: Wednesday, August 31, 2022 8:07 AM
To: [email protected] <[email protected]>
Subject: Re: [TWS API] US market Index contact name
?

You will encounters this issue more than once, I suggest you master the API reqMatchingSymbols
witch give you¡¯re a bridge between human form and IBKR form, you can use "NDX", "SMART", "IND" "USD" for the proxy of contract to narrow the answers
To shorten your work, hereafter an extract of a few combinations,

Symbol, Exchange, Type, Conid
...

"SPX",? "CBOE",?????? "IND", 416904,?????????? // S&P 500 INDEX???? ??? ??? ??? ??? ? IBK CBOE
"INDU", "CME",???????? "IND", 1935181,??? ???? // Dow Jones Industrial Average IBK CBOE
"RUT",? "RUSSELL", "IND", 416888,??? ?????? // RTY Russell 2000??? ??? ??? ??? ??? IBK CBOE
"T1X",?? "LSE",???????? ? "IND", 38705743??? ?? // FTSE 100 Index??? ??? ??? ??? ??? ?? Require permission
"VIX",??? "CBOE",?????? "IND", 13455763,??? ?? // VIX
"NDX",? "NASDAQ",? "IND", 416843,?? ? ? ? ? // NDX

...

Russell is the oddest, no way to guess the exchange (at least for me) without using reqMatchingSymbols


Close open positions

 

Hello,
I spent a few days trying to find the cause of my issue unsuccessfully. I hope someone could kindly point me into the right direction.
I am transferring my script from the old version api (9.x) to the new one (10.x).
Previously, I could close open positions with the following code (I will skip non-relevant code to save the space):
???
??? def position(self, account: str, contract: Contract, position: float, avgCost: float):
??????? super().position(account, contract, position, avgCost)
??????? print("Position.", "Account:", account, "Symbol:", contract.symbol, "SecType:",
???????????? contract.secType, "Currency:", contract.currency, "Position:", position,
???????????? "Avg cost:", avgCost)
?????? ?
??????? if position != 0:
??????????? order = Order()
??????????? order.orderType = 'MKT'
??????????? order.totalQuantity = abs(position)
??????????? order.action = ('BUY', 'SELL')[position > 0]
?????????? ?
??????????? contract = Contract()
??????????? contract.symbol = "GBP"
??????????? contract.secType = "CASH"
??????????? contract.exchange = "IDEALPRO"
??????????? contract.currency = "USD"
?????????? ?
??????????? self.placeOrder(self.nextOrderId+2, contract, order)
??????????? print('All positions are closed')
??????? else:
??????????? print('There are no open positions')
?????? ?
??? def positionEnd(self):
??????? super().positionEnd()
??????? print("PositionEnd")
?????? ?
??? def start(self):
? ? ? ? # Some Order() and Contract() code here
??????
??????? with open('previous_order.txt') as file:
??????????? prev_order = int(file.read())
??????? if trend == prev_order:
??????????? pass
??????? else:
??????????? self.reqPositions()
??????????? self.reqGlobalCancel()
??????
??????? #Open a new order here
?????? ?
??? def stop(self):
??????? self.done = True
??????? self.disconnect()


That worked fine - when it goes with the trend the code would open a new order, but if the trend was changed, the code would close open positions (with a single MKT order) and open a new order in another direction.
But in the new version that does not work. I checked the code without closing open positions - everything works as expected, I can open a new order. But when I use the code to close open positions it goes crazy by opening a lot of new MKT orders. Like going through the loop.

The new code:

??? def position(self, account: str, contract: Contract, position: Decimal, avgCost: float):
??????? super().position(account, contract, position, avgCost)
??????? print("Position.", "Account:", account, "Symbol:", contract.symbol, "SecType:", contract.secType,
????????????? "Currency:", contract.currency, "Position:", position,
????????????? "Avg cost:", avgCost)
???????
??????? if position != 0:
??????????? close_order = Order()
??????????? close_order.orderType = 'MKT'
??????????? close_order.totalQuantity = abs(position)
??????????? close_order.action = ('BUY', 'SELL')[position > 0]
?????????? ?
??????????? contract = Contract()
??????????? contract.symbol = "GBP"
??????????? contract.secType = "CASH"
??????????? contract.exchange = "IDEALPRO"
??????????? contract.currency = "USD"
?????????? ?
??????????? self.placeOrder(self.nextOrderId(), contract, close_order)
??????????? print('All positions are closed')
??????? else:
??????????? print('No positions to close')
?????? ?
??? def positionEnd(self):
??????? super().positionEnd()
??????? print("PositionEnd")

??? def start(self):
??????? result = 'short' # For testing
??????? with open('/home/alex/Documents/Auto/IB/previous_order.txt') as file:
??????????? prev_order = file.read()
??????? if result == prev_order:
??????????? print('result check')
??????????? pass?????? ?
??????? elif result == 0:
??????????? self.disconnect()
??????? else:
??????????? self.reqPositions()
??????????? self.reqGlobalCancel()

??? def stop(self):
??????? self.disconnect()???


I attached the truncated log file as well.
Thank you very much in advance.


Re: US market Index contact name

 

You will encounters this issue more than once, I suggest you master the API reqMatchingSymbols
witch give you¡¯re a bridge between human form and IBKR form, you can use "NDX", "SMART", "IND" "USD" for the proxy of contract to narrow the answers
To shorten your work, hereafter an extract of a few combinations,

Symbol, Exchange, Type, Conid
...

"SPX",? "CBOE",?????? "IND", 416904,?????????? // S&P 500 INDEX???? ??? ??? ??? ??? ? IBK CBOE
"INDU", "CME",???????? "IND", 1935181,??? ???? // Dow Jones Industrial Average IBK CBOE
"RUT",? "RUSSELL", "IND", 416888,??? ?????? // RTY Russell 2000??? ??? ??? ??? ??? IBK CBOE
"T1X",?? "LSE",???????? ? "IND", 38705743??? ?? // FTSE 100 Index??? ??? ??? ??? ??? ?? Require permission
"VIX",??? "CBOE",?????? "IND", 13455763,??? ?? // VIX
"NDX",? "NASDAQ",? "IND", 416843,?? ? ? ? ? // NDX

...

Russell is the oddest, no way to guess the exchange (at least for me) without using reqMatchingSymbols


Re: US market Index contact name

 

Did you try using info from the TWS screen?

1)Type SPX in watchlist
?2) Select SPX index from the results list
3) Double-click on SPX row to show additional details.? If you notice, exchange is not SMART but is CBOE.


Re: Market of Euronext-Amsterdam (AEB) but somehow it stopped

 

Hello,

I have the same issue regarding Euronext French Stocks.
Just for your information, if you monitor these instruments through TWS GUI, then you're able to subscribe to market data through the API.

Not a great solution, but it could help temporarily if you really need these data.

Regards
Loic


US market Index contact name

 

¿ªÔÆÌåÓý

Hi all,

Can someone please share the contract symbol for US market indexes (or where to find them)?

This does not work:

? ? def Index_Contact():
? ? ? ? contract = Contract()
? ? ? ? contract.symbol = "SPX"
? ? ? ? contract.secType = "IND"
? ? ? ? contract.currency = "USD"
? ? ? ? contract.exchange = "SMART"
? ? ? ? return contract

I'd like to know symbols for "SPX", "NDX" and "RUT". Thanks!


Re: suggestions for simple GUI : IBAPI - python - windows

 

This might be more than you bargained for, but it's what I came up with to solve the problem you are facing.? When I started this I was new to Python, new to object oriented programming and new to IB API, so I'm sure there are better/more efficient ways to do this.
The trick is the UI needs to be created before IB API or you won't be able to update any variables in the UI from the API...BUT... the tkinter mainloop must be executed last because no processing will occur after mainloop is run.? ?
I'm submitting this because I really struggled with your question, so hopefully this helps you and others.

This template has the following characteristics:
  1. The program main function creates an instance of tkinter
  2. The tkinter frames are then created?
  3. An instance of the IB API is created
  4. The tkinter mainloop is run
  5. Steps 2-4 execute with the tkinter constructor (__init__)
  6. In the IBAPI initialization, a field in the UI is updated to show that it worked.
  7. As an added bonus, there is some code to wait for an actual connection to TWS before continuing (rather than just wait 1 or 2 seconds).? This is what the?orderIdAvailable stuff is about.
Here it is:
#########################################################################################################
# Name: ib_tkinter_template.py
# Author: Steve Tuscher
# Date: 30 AUG 2022
# Description: Template program to connect to TWS from tkinter
#########################################################################################################
# imports
from tkinter import *
from tkinter import ttk
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
import threading
import datetime
?
#########################################################################################################
# Tkinter User Interface class
#########################################################################################################
class TkUi():
? ? def __init__(self):
? ? ? ? self.root = Tk()
? ? ? ? self.root.geometry('500x100')
? ? ? ? self.root.title("Tkinter and IB API Template App")
?
? ? ? ? # Create the actual UI? ??
? ? ? ? self.create_frames()
?
? ? ? ? # Connect to TWS?
? ? ? ? self.connect_to_TWS()
?
? ? ? ? # This has to be last
? ? ? ? self.launch_UI()
?
? ? # Create the UI frames
? ? def create_frames(self):
? ? ? ? # Frame1 is for the buttons
? ? ? ? self.frame1 = ttk.LabelFrame(self.root, padding=("8 10 8 10"))
? ? ? ? self.frame1.grid(column=1, row=1, sticky=(N, W, E, S))
? ? ? ? outputRow = 1
? ? ? ? quit_button = ttk.Button(self.frame1, text="QUIT", command=self.quit)
? ? ? ? quit_button.grid(row=outputRow, column=1, sticky=(W, E))
?
? ? ? ? outputRow += 1
? ? ? ? self.testField = StringVar()
? ? ? ? ttk.Label(self.frame1, textvariable=self.testField).grid(row=outputRow, column=1, sticky=(W))
?
?
? ? # Launch the UI
? ? def launch_UI(self):
? ? ? ? self.root.mainloop()
?
? ? # Quit button?
? ? def quit(self):
? ? ? ? try:
? ? ? ? ? ? self.client.disconnect()
? ? ? ? except:
? ? ? ? ? ? self.log("Unable to disconnect.")
? ? ? ? quit()
?
? ? # Connect to TWS
? ? def connect_to_TWS(self):
? ? ? ? self.client = IbApi(self)
? ? ? ? self.client.connect("127.0.0.1",? 7497, 0)
? ? ? ? thread = threading.Thread(target = self.client.run)
? ? ? ? thread.start()
? ? ? ? # Wait until an orderID is returned from TWS
? ? ? ? if not orderIdAvailable.wait(timeout=10):
? ? ? ? ? ? print("Connection to TWS failed at ", datetime.datetime.now().strftime("%H:%M:%S"))
? ? ? ? ? ? quit()
?
#########################################################################################################
# TWS API Class
#########################################################################################################
class IbApi(EWrapper, EClient):
? ? def __init__(self, tkUi):
? ? ? ? super().__init__()
? ? ? ? EClient.__init__(self, self)
? ? ? ? EWrapper.__init__(self)
? ? ? ? self.tkUi = tkUi
? ? ? ? self.tkUi.testField.set("IB API started.")
?
? ? def nextValidId(self, orderId: int):
? ? ? ? super().nextValidId(orderId)
? ? ? ? orderIdAvailable.set()
? ? ? ? self.nextValidOrderId = orderId
? ? ? ? print("NextValidId:", orderId)
?
#########################################################################################################
# Begin Mainline
#########################################################################################################
def main():
? ? TkUi()
?
if __name__ == '__main__':
? ? orderIdAvailable = threading.Event()
? ? main()
?


Re: suggestions for simple GUI : IBAPI - python - windows

 

¿ªÔÆÌåÓý

before I moved from python to julia I looked at the "async streaming ticks" approach that the great Ewald created. Insync is a GREAT approach to coding to the Tws api.

here's the blurb on insync



On 8/30/22 04:13, Erez Kaplan wrote:

Hi,

?

I would like my code to be able to display and update information from time to time. ( in a simple GUI / table )

I tried tkInter but had problems with its main? loop.

?

Any suggestions (preferably with examples) of how to incorporate such a simple GUI without disrupting the EWrapper, EClient?

IBAPI - python - windows

?

Cheers, Erez

?

?

?


suggestions for simple GUI : IBAPI - python - windows

Erez Kaplan
 

Hi,

?

I would like my code to be able to display and update information from time to time. ( in a simple GUI / table )

I tried tkInter but had problems with its main? loop.

?

Any suggestions (preferably with examples) of how to incorporate such a simple GUI without disrupting the EWrapper, EClient?

IBAPI - python - windows

?

Cheers, Erez

?

?

?


Re: check if running in Paper or Live trading mode programatically

 

That's very simple.?? Papertrading-Accounts start with a "D" , DFxxx are advisor accounts, DUxxx user accounts

(in Ruby):?

?? ?def test_environment?
?? ???? ??? !!(account =~ /^[D]{1}/)
?? ???? end

Accounts are available through ReqManagedAccounts, which returns a comma separated string of connected accounts.

Don't rely on the port. this can be set by the user.


Re: Why is my reqMktData thread not running with IB TWS Python API?

 

I meant to print something inside the?def streamData(): method so you can see that it has been run once. I don't expect it to be alive after it has run.


Re: Why is my reqMktData thread not running with IB TWS Python API?

papuchon
 

Tried printing and it is working (see screenshot), I am getting the pricing data correctly BUT it still says the thread is not alive.. any other idea/clue from anyone? Really stuck on this one. Any help from a python TWS IB API expert appreciated


Re: Shortable instruments

 

Well, according to there are two ticks that tell you whether an instrument is shortable:
  • Tick #46 "Shortable" can be used as a "green", "yellow", "red" flag
  • Tick #89 "ShortableShares" tells you how many shares are available available for shorting

We don't use these for decision making so I can't tell you how good the data is. But when I look at last week's data logs the values we received for stocks and ETFs make sense.

´³¨¹°ù²µ±ð²Ô


Re: check if running in Paper or Live trading mode programatically

 

When your client connects to TWS/IBGW it receives callback with a list of the accounts the client application can trade through that connection. That list, obviously, depends on the active login TWS/IBGW has with IBKR at the time of client connection. So you can tell your client application which accounts are paper accounts and which ones are live accounts.

I could swear I have seen an IBKR Knowledge Base article in the past where they described how account numbers for various account types are structured but could not find it right now (maybe someone has a link handy?) If I remember correctly, paper accounts can be identified by their account number as well.

´³¨¹°ù²µ±ð²Ô


Re: check if running in Paper or Live trading mode programatically

 

Check the connecting port number