Keyboard Shortcuts
Likes
- Twsapi
- Messages
Search
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); |
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):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 "SPX",? "CBOE",?????? "IND", 416904,?????????? // S&P 500 INDEX???? ??? ??? ??? ??? ? IBK CBOE ... 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 "SPX",? "CBOE",?????? "IND", 416904,?????????? // S&P 500 INDEX???? ??? ??? ??? ??? ? IBK CBOE ... Russell is the oddest, no way to guess the exchange (at least for me) without using reqMatchingSymbols |
Re: Market of Euronext-Amsterdam (AEB) but somehow it stopped
Hello, Not a great solution, but it could help temporarily if you really need these data. |
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:
#########################################################################################################
# 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:
|
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? ? 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?
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:
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. ´³¨¹°ù²µ±ð²Ô |