Keyboard Shortcuts
Likes
- Twsapi
- Messages
Search
How to get specific data (like Open, High, Low) of Options using TWS reqContractDetails()?
Hi,
I am using the following code to get Options Data using TWS: I just print the response now, the code looks like this: Which returns a bunch of output as: 513350726,MSFT,OPT,20211029,345.0,C,100,SMART,,USD,MSFT? 211029C00345000,MSFT,False,,combo:,MSFT,0.01,ACTIVETIM,AD,ADJUST,ALERT,ALGO,ALLOC,AVGCOST,BASKET,COND,CONDORDER,DAY,DEACT,DEACTDIS,DEACTEOD,DIS,FOK,GAT,GTC,GTD,GTT,HID,ICE,IOC,LIT,LMT,MIT,MKT,MTL,NGCOMB,NONALGO,OCA,OPENCLOSE,PEGMIDVOL,PEGMKTVOL,PEGPRMVOL,PEGSRFVOL,POSTONLY,PRICECHK,REL,RELPCTOFS,RELSTK,SCALE,SCALERST,SIZECHK,SNAPMID,SNAPMKT,SNAPREL,STP,STPLMT,TRAIL,TRAILLIT,TRAILLMT,TRAILMIT,VOLAT,WHATIF,SMART,AMEX,CBOE,PHLX,PSE,ISE,BOX,BATS,NASDAQOM,CBOE2,NASDAQBX,MIAX,GEMINI,EDGX,MERCURY,PEARL,EMERALD,1,272093,MICROSOFT CORP,202110,Technology,Software,Applications Software,US/Eastern,20211018:0930-20211018:1600;20211019:0930-20211019:1600;20211020:0930-20211020:1600;20211021:0930-20211021:1600;20211022:0930-20211022:1600,20211018:0930-20211018:1600;20211019:0930-20211019:1600;20211020:0930-20211020:1600;20211021:0930-20211021:1600;20211022:0930-20211022:1600,,0,1,MSFT,STK,32,109,109,109,109,109,109,109,32,109,32,109,109,109,109,109,109,2,None,20211029,,,,,,,False,False,0,False,,,,,False,As there is no heading so I have no idea what actually those data mean. I just need to receive Open, Close, High, Low. Can anyone help me how can I extract exact information from the response? - Thanks |
Re: Sending multiple orders
Thank you for your answer.
I did the changes, and now multiple orders are being send. I added more tickers to my list, and it's sending as many orders as I have in my list. But unfortunately,? the orders are being sent wrongly. Instead of sending an order for 'GOOG', then 'AAPL' and finally 'MSFT', it's sending 'GOOG' and then 'AAPL' and 'AAPL... Another member told me to check with the orderId and reqId, and that it might create a problem with the increment of the next valid order Id. I did some changes which worked for about 10 min, and then my problem came back. I tried to make some changes but it's still doesn't work... Here is the code -------------------------------------------------------------------------- ?# Imports for the Program from ibapi.client import EClient from ibapi.wrapper import EWrapper from ibapi.contract import Contract from ibapi.order import Order from ibapi.utils import iswrapper import time import threading import sys class TestLimitOrder(EWrapper, EClient): ? ? ''' Serves as the Client and the Wrapper ''' ? ? def __init__(self, addr, port, client_id): ? ? ? ? EWrapper.__init__(self) ? ? ? ? EClient.__init__(self, self) ? ? ? ? self.orderId = None ? ? ? ? # Connect to TWS API ? ? ? ? self.connect(addr, port, client_id) ? ? ? ? # Launch the client thread ? ? ? ? thread = threading.Thread(target=self. ? ? ? ? thread.start() ? ? @iswrapper ? ? def nextValidId(self, orderId): ? ? ? ? ''' Provides the next order ID ''' ? ? ? ? self.orderId = orderId ? ? ? ? print('\nThe order id is: {}'.format(orderId)) ? ? @iswrapper ? ? def openOrder(self, orderId, contract, order, state): ? ? ? ? ''' Callback for the submitted order ''' ? ? ? ? print('Order Status: {}'.format(state.status)) ? ? ? ? print('The accounts current initail margin: {}'.format(state. ? ? ? ? print('The accounts current maintanence margin: {}'.format(state. ? ? ? ? print('Comission Charged: {}'.format(state.commission)) ? ? ? ? print('Completed Time: {}'.format(state. ? ? ? ? print('Warning Text: {}'.format(state.warningText)) ? ? @iswrapper ? ? def orderStatus(self, orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, ? ? ? ? ? ? ? ? ? ? whyHeld, mktCapPrice): ? ? ? ? ''' Check the status of the submitted order ''' ? ? ? ? print('Status of Order: {}'.format(status)) ? ? ? ? print('No. of Filled Positions: {}'.format(filled)) ? ? ? ? print('No. of remaining positions: {}'.format(remaining)) ? ? ? ? print('Why Held: {}'.format(whyHeld)) ?# value 'locate'used when trying to locate shares for short sell ? ? ? ? print('Average Fill Price: {}'.format(avgFillPrice)) ? ? ? ? print('permId: {}'.format(permId)) ? ? @iswrapper ? ? def error(self, reqId, code, msg): ? ? ? ? print('Error Code: {}'.format(code)) ? ? ? ? print('Error Message: {}'.format(msg)) def run_loop(): ? ? # Create the client and Connect to TWS API ? ? global contract ? ? client = TestLimitOrder('127.0.0.1', 7497, 7) ? ? time.sleep(3) ? ? client.orderId = 1 ? ? api_thread = threading.Thread(target=run_ ? ? api_thread.start() ? ? symbols = ['GOOG', 'AAPL', 'MSFT'] ? ? reqId = 1 ? ? sym_dict = {} ? ? for sym in symbols: ? ? ? ? # Define a Contract ? ? ? ? contract = Contract() ? ? ? ? contract.symbol = str(sym) ? ? ? ? sym_dict[reqId] = sym ? ? ? ? contract.secType = 'STK' ? ? ? ? contract.exchange = 'SMART' ? ? ? ? contract.currency = 'USD' ? ? ? ? reqId += 1 ? ? ? ? reqId +=2 ? ? ? ? time.sleep(3) ? ? ? ? # Define the Limit Order for BUY/SELL ? ? ? ? order = Order() ? ? ? ? order.action = 'BUY' ? ? ? ? order.totalQuantity = 1 ? ? ? ? order.orderType = 'MKT' ? ? ? ? # Request from TWS, the next valid ID for the order ? ? ? ? client.reqIds(+1) ? ? ? ? time.sleep(3) ? ? ? ? # Place the order ? ? ? ? if client.orderId: ? ? ? ? ? ? client.placeOrder(client. ? ? ? ? ? ? time.sleep(3) ? ? ? ? ? ? reqId+=1 ? ? ? ? ? ? time.sleep(3) ? ? ? ? ? ? reqId+=2 ? ? ? ? else: ? ? ? ? ? ? print('Order ID not received. Terminating Application') ? ? ? ? ? ? sys.exit() ? ? ? ? # Disconnect from TWS ? ? ? ? time.sleep(3) ? ? ? ? client.disconnect() if __name__ == "__main__": ? ? run_loop() ---------------------------------------------------------------------------- |
Re: Scanning with IABSocketAPI in C++ Builder
Nick
¿ªÔÆÌåÓýI doubt anyone here will be able to help since almost everyone uses one of the IB supplied libraries. Your best best would be to contact the library developer if they
are still around. On 10/18/2021 1:23 PM, Colin B Maharaj
wrote:
|
Scanning with IABSocketAPI in C++ Builder
¿ªÔÆÌåÓýHi, I am using IABSocketAPI from hhssoftware.com and trying to do a gap scanner. After months, I cant get the code working Note: I dont do python, of Visual studio or Java. I got the hhssoftware software component that I was able to successfully install in C++ Builder , but I dont get a response from my event. Below is the code I have to create the scanner. and below that the onScannerData event Any help will be appreciated thanks. //------------------------------------------------------------------------------ TIABScanCriteria * ScanCriteria=NULL; int ScanId = 2; int sCount=0; void __fastcall TForm4::InitScannerClick(TObject *Sender) { ?? sCount=0; ?? ScanCriteria = new TIABScanCriteria; ?? ScanCriteria->StockTypeFilter = "CORP"; ?? ScanCriteria->NumberOfRows = 20; ?? ScanCriteria->Instrument = "STK"; ?? ScanCriteria->LocationCode = "STK.NYSE"; ?? ScanCriteria->AbovePrice = 1.0; ?? ScanCriteria->BelowPrice = 15.0; ?? ScanCriteria->ScanCode = "TOP_PERC_GAIN"; ?? ScannerSelect1->Enabled = false; ?? InitScanner->Enabled = false; ?? StopScanner->Enabled = true; ?? IABSocket1->Scanner->InitializeScanCriteria(ScanCriteria); ?? IABSocket1->Scanner->NewScan(ScanId, *ScanCriteria); } //--------------------------------------------------------------------------- void __fastcall TForm4::IABSocket1ScannerData(TObject *Sender, TIABScan *Scan) { ?? int qr = Scan->Count+1; ?? if (qr==1) { qr=2; } ?? Grid2->RowCount =qr; ?? Label4->Caption = sCount++; ?? Grid2->Cells[0][0]="Symbol"; ?? Grid2->Cells[1][0]="Rank"; ?? Grid2->Cells[2][0]="MarketName"; ?? Grid2->Cells[3][0]="TradingClass"; ?? Grid2->Cells[4][0]="LocalSymbol"; ?? for (int i = 0; i< Scan->Count; i++) ?? { ???? TIABScanResultItem * s = Scan->Items[i]; ???? Grid2->Cells[0][i+1] = s->Symbol; ???? Grid2->Cells[1][i+1] = s->Rank; ???? Grid2->Cells[2][i+1] = s->MarketName; ???? Grid2->Cells[3][i+1] = s->TradingClass; ???? Grid2->Cells[4][i+1] = s->LocalSymbol; ?? } } |
Re: MOC orders and ocaGroup
MOC orders can be placed in OCA groups in unprotected-reduce mode. That's the single mode that has worked in my experience?with MOC orders, with an additional caveat that the closing order will likely not actually be reduced at any stage but only cancelled completely once the other order is completely filled.
|
Re: Sending multiple orders
The code (as you've shown it) only iterates the definition of the contract.? The rest of the code (defining the order, reqId, placeOrder) is only called once.? You need to indent the relevant sections so they are included in the iteration.? Something like:
for sym in symbols: |
Sending multiple orders
Hey guys, newbie here. I have been working on the tws api with python for two months now, and for the past two weeks I've been trying to send multiple orders at once. But unfortunately only the last ticker of my list is being send. In this case, I have 'GOOG' and 'AAPL' in my list, but only 'AAPL' is received and placed as an order.
I looked everywhere and I just can't find a solution for this. Does anyone see where the problem is with my code ? ----------------------------------------------------------------------------------------------------------------------------------- # Imports for the Program
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.order import Order
from ibapi.utils import iswrapper
?
import time
import threading
import sys
?
?
class TestLimitOrder(EWrapper, EClient):
? ? ''' Serves as the Client and the Wrapper '''
?
? ? def __init__(self, addr, port, client_id):
? ? ? ? EWrapper.__init__(self)
? ? ? ? EClient.__init__(self, self)
? ? ? ? self.orderId = None
?
? ? ? ? # Connect to TWS API
? ? ? ? self.connect(addr, port, client_id)
?
? ? ? ? # Launch the client thread
? ? ? ? thread = threading.Thread(target=self.run)
? ? ? ? thread.start()
?
? ? @iswrapper
? ? def nextValidId(self, orderId):
? ? ? ? ''' Provides the next order ID '''
? ? ? ? self.orderId = orderId
? ? ? ? print('\nThe order id is: {}'.format(orderId))
?
? ? @iswrapper
? ? def openOrder(self, orderId, contract, order, state):
? ? ? ? ''' Callback for the submitted order '''
? ? ? ? print('Order Status: {}'.format(state.status))
? ? ? ? print('The accounts current initail margin: {}'.format(state.initMarginBefore))
? ? ? ? print('The accounts current maintanence margin: {}'.format(state.maintMarginBefore))
? ? ? ? print('Comission Charged: {}'.format(state.commission))
? ? ? ? print('Completed Time: {}'.format(state.completedTime))
? ? ? ? print('Warning Text: {}'.format(state.warningText))
?
? ? @iswrapper
? ? def orderStatus(self, orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId,
? ? ? ? ? ? ? ? ? ? whyHeld, mktCapPrice):
? ? ? ? ''' Check the status of the submitted order '''
? ? ? ? print('Status of Order: {}'.format(status))
? ? ? ? print('No. of Filled Positions: {}'.format(filled))
? ? ? ? print('No. of remaining positions: {}'.format(remaining))
? ? ? ? print('Why Held: {}'.format(whyHeld))? # value 'locate'used when trying to locate shares for short sell
? ? ? ? print('Average Fill Price: {}'.format(avgFillPrice))
? ? ? ? print('permId: {}'.format(permId))
?
? ? @iswrapper
? ? def error(self, reqId, code, msg):
? ? ? ? print('Error Code: {}'.format(code))
? ? ? ? print('Error Message: {}'.format(msg))
?
?
?
def run_loop():
? ? # Create the client and Connect to TWS API
? ? global contract
? ? client = TestLimitOrder('127.0.0.1', 7497, 7)
? ? time.sleep(3)
? ? client.orderId = None
? ? api_thread = threading.Thread(target=run_loop, daemon=True)
? ? api_thread.start()
?
?
? ? symbols = ['GOOG','AAPL']
? ? reqId = 1
? ? sym_dict = {}
?
? ? for sym in symbols:
? ? ? ? # Define a Contract
? ? ? ? contract = Contract()
? ? ? ? contract.symbol = str(sym)
? ? ? ? sym_dict[reqId] = sym
? ? ? ? contract.secType = 'STK'
? ? ? ? contract.exchange = 'SMART'
? ? ? ? contract.currency = 'USD'
? ? ? ? reqId += 1
?
? ? time.sleep(3)
?
? ? # Define the Limit Order for BUY/SELL
? ? order = Order()
? ? order.action = 'BUY'
? ? order.totalQuantity = 1
? ? order.orderType = 'MKT'
?
?
? ? # Request from TWS, the next valid ID for the order
? ? client.reqIds(+1)
? ? time.sleep(3)
?
?
?
? ? # Place the order
?
? ? if client.orderId:
? ? ? ? client.placeOrder(client.orderId+1, contract, order)
? ? ? ? time.sleep(3)
? ? else:
? ? ? ? print('Order ID not received. Terminating Application')
? ? ? ? sys.exit()
?
?
? ? # Disconnect from TWS
? ? time.sleep(3)
? ? client.disconnect()
?
?
if __name__ == "__main__":
? ? run_loop()
--------------------------------------------------------------------------------------------------------------------- ?
? |
Re: MOC orders and ocaGroup
Nick
You'll probably have to talk to IB to get an official answer.
toggle quoted message
Show quoted text
If I remember right MOC orders can't be modified within 10 minutes of the close. Cancelling one of the other orders in this time would result in just the MOC order remaining live which would leave you with an incomplete group. IB may be trying to prevent this situation and so disallows MOC orders in OCA groups. On 10/15/2021 1:19 AM, David Walker wrote:
Has anyone worked out how to handle MOC (Market on Close) orders inside an ocaGroup? |
Re: MOC orders and ocaGroup
Great suggestion, thanks ´³¨¹°ù²µ±ð²Ô. Manually keying a MOC order in an ocaGroup with a trailing stop and a limit stop gives these errors:
Reduce others:? OCA handling method mismatch Reduce others (overfill):? Invalid OCA handling method Cancel others: Invalid OCA handling method It would seem to indicate MOC orders can't operate in an ocaGroup; but the error message are odd, as they seem to imply that there is a valid way of doing it. |
Re: MOC orders and ocaGroup
Does TWS allow your construct when you key that in manually?
Reason why I ask is that I just went through a debug cycle for a very similar issue. In my case it was a MKT order with TimeCondition set to five minutes before market close that failed when transmitted in an OCA group. But it worked when entered in TWS through the "Order Ticket" screen in TWS. So I compared the order object that I submitted via the API with the one that TWS created and quickly found the initialization issue in my code. ´³¨¹°ù²µ±ð²Ô |
MOC orders and ocaGroup
Has anyone worked out how to handle MOC (Market on Close) orders inside an ocaGroup?? There doesn't seem to be a valid ocaType setting for a MOC order: 1 & 2 return error 201 ("Order rejected - reason:Invalid OCA handling method."), and I don't want to use/haven't tried 3.
I can work around this of course by manually (via code) cancelling other orders in the group and submitting the MOC as a standalone order, but I'm surprised that the API requires this.? In any case it's not ideal, because I would like the other orders (stops) to remain in place until the MOC order triggers.? Is there no way for a MOC order to sit inside a ocaGroup? |
Re: Version 10.10 of Gateway.
¿ªÔÆÌåÓýDon't worry. That option is not needed for the Gateway because it really only exists for use of the API, so it always allows socket-based technologies such as ActiveX and the new DDE Bridge. ? So it just works¡ ? From: [email protected] <[email protected]> On Behalf Of polomora@...
Sent: 13 October 2021 00:51 To: [email protected] Subject: Re: [TWS API] Version 10.10 of Gateway. ? Sorry for highjacking the original message content. On IB Gateway, this option is missing! Under Configuration -> API -> Settings, all I see is a linked message "DDE replaced with DDE Bridge connecting via TWS Socket API". WHen I click on this link, I get redirected to an IB webpage page, which displays the following. This implies that the the ActiveX and SocketCLients option is still? supported. Steps to launch DDE server
?
|
Re: Version 10.10 of Gateway.
Sorry for highjacking the original message content. On IB Gateway, this option is missing! Under Configuration -> API -> Settings, all I see is a linked message "DDE replaced with DDE Bridge connecting via TWS Socket API". WHen I click on this link, I get redirected to an IB webpage page, which displays the following. This implies that the the ActiveX and SocketCLients option is still? supported. Steps to launch DDE server
|
Re: Wednesday night TWS restart not clean - stuck in "Initializing managers..." and purple grids
Thanks for the prompt responses. I am not sure if/how its connected to daily resets or daily restarts. I have tried restarts before resets as well ( 8 PM PST) and thats when I noticed this first. So I then moved the daily restart past the resets ( 9:50 pm PST) so if it was due to the resets, then hoping the restart would fix it. But its still happening on and off. I have switched machines as well. It could be something on my network - but I cannot imagine that my network is down all night long. When this happened last Wednesday night, my TWS log was full of the below all night long - till I restarted TWS early morning Thursday.
2021-10-07 06:23:42.605 [RN] INFO? [JTS-Fuse-usbond-nativepause-304130] - Starting fuse [name=usbond-nativepause,timeout=1000]...
2021-10-07 06:23:42.605 [RN] INFO? [JTS-Fuse-cashhmds-nativepause-304131] - Starting fuse [name=cashhmds-nativepause,timeout=1000]...
2021-10-07 06:23:42.606 [RN] INFO? [JTS-Fuse-fundfarm-nativepause-304132] - Starting fuse [name=fundfarm-nativepause,timeout=1000]...
2021-10-07 06:23:42.607 [RN] INFO? [JTS-Fuse-eufarm-nativepause-304133] - Starting fuse [name=eufarm-nativepause,timeout=1000]...
2021-10-07 06:23:42.611 [RN] INFO? [JTS-Fuse-secdefil-ccppause-304134] - Starting fuse [name=secdefil-ccppause,timeout=1000]...
2021-10-07 06:23:42.612 [RN] INFO? [JTS-Fuse-jfarm-nativepause-304135] - Starting fuse [name=jfarm-nativepause,timeout=1000]...
2021-10-07 06:23:42.613 [RN] INFO? [JTS-Fuse-hfarm-nativepause-304136] - Starting fuse [name=hfarm-nativepause,timeout=1000]...
2021-10-07 06:23:42.614 [RN] INFO? [JTS-Fuse-euhmds-nativepause-304137] - Starting fuse [name=euhmds-nativepause,timeout=1000]...
2021-10-07 06:23:42.615 [RN] INFO? [JTS-Fuse-ushmds-ccppause-304138] - Starting fuse [name=ushmds-ccppause,timeout=1000]... The one thing is that I have hundreds of OCA orders open at any given time - (swing trades on weekly/monthly timeframes), and not sure if this trips up TWS because I see lots of messages about processing orders etc in the TWS log aswell and some ArrayOutofBoundsException etc...Well, lets see if it happens this week and then I can upload some diagnostics to IB. |
Re: Wednesday night TWS restart not clean - stuck in "Initializing managers..." and purple grids
As Nick already suggested, you might want to move your daily restart time a little. Maybe past midnight your time or after the markets have closed. We moved ours to 16:45 US/Central a while back and had no problems since. Restarting at 21:50 PST is past the IB maintenance window (20:45 PST to 21:45 PST) and should work every time, but IB has occasionally had outages outside of that window. In fact our logs from the last few years have seen error 1100/1102 pairs in pretty much every 5min interval around the clock. Not knowing your setup, is there a chance that issues with your network connection cause TWS's inability to restart? Maybe WIFI, router, ISP problems? I quickly grabbed the disconnect/reconnect data for YTD2021 and the distribution looks like this (we are connected to IB's east coast servers): On Wednesdays in 2021, IB disconnects never took place before 23:21 or after 23:39 (US/Central): |
Unpicking Java API 10.10.04
Going through the code now as it's broken my Clojure wrapper. Here are a few findings that may help others. Please chime in if you've found other problems, my daily usage covers such a small area of the API that I may well have missed a lot.
There is yet more encapsulation. The biggest culprit seems to be a new Decimal class, that encapsulates java BigDecimal and is now found throughout the code. Volumes and wap in the Bar class now have this type, as well as all the tick size data. So we're moving from primitives to wrappers which is breaking a lot of stuff. More enums - rather a good thing I guess. There is a SecType CRYPTO. More AccountData fields. There is a contracts module with ComboContract / FutContract / OptContraact / StkContract that seem to come with appropriate defaults. Notably FutContract uses exchange "ONE" which I'd hope is the default right exchange for the future contract. |
Re: How to connect to TWS from server side
Matthias Frener
On Mon, Oct 11, 2021 at 12:27 PM, John Griessen wrote:
Is your middleware a python script looping and doing the REST commands, or something more heavy? >?Is your middleware a python script looping and doing the REST commands, or something more heavy? |
Re: How to connect to TWS from server side
On 10/11/21 11:06, Matthias Frener wrote:
> And what of using autorestart mechanism provided by TWS 974? Does that make IBC obsolete?That sounds compatible with the latest from IBKR where they say a new login is needed weekly. Is your middleware a python script looping and doing the REST commands, or something more heavy? I'll look for some discussions about "IBC is about to automate UI interaction with Gateway". Thanks for telling how a stable high uptime method for connecting to IBKR is possible. |