Purebasic and TWS 20
Hi, I am looking for Purebasic source code that uses TWS API. I am a begineer in Purebasic and TWS but not in programming but dont really know where to start. For example do I have to: 1 - Load a DLL such as TWSAPI.DLL or TWSLib.dll or something else, and then call the included functions? 2 - Open a windows socket connection and then send command strings ? I tryed to find out exploring source code in other languages, but nothing appeared clearly to me. My feeling is that Purebasic is a good language for this use as it generates a very compact and efficient executable file with no depencies. I just need to get started, then I can manage the rest. However if I could find Purebasic source code I might save a lot of time. Thanking you in advance for any help.
Розпочато Tradiator @ · Останніх @
TWS API - TICK Historical Candles issue AFTER November 25th
Hi, I am trying to retrieve historical price data of a few FOREX currency pairs: mainly AUDCAD, EURUSD and EURGBP. Since November 25th, I am unable to retrieve historical TICK data via API. Before that date, I was able to download any price even going back to 2022. When trying to download TICK data, I am getting the following error: Historical Market Data Service error message:HMDS query returned no data: <SYMBOL@TYPE OF PRICE> I get the error regardles if it's: CASH or CFD IDEAPRO or SMART ASK BID BID_ASK_MIDPOINT price What I tried: 1. I tried and I CAN download 30 SEC candles meaning that it is not a problem with the code, connection or ports. 2. I used another account and another IP. 3. I tried different DATE formats, e.g. yyyyMMdd-HH:mm:ss I am running out of options. Can you please help me understand what might be the problem?
Розпочато konrad.patynski@... @
How do I find out the margin requirements for a US stock through the TWS API? 9
Hi, I'd like to find out the margin requirements for US stocks via the TWS API in python. On the Trader Workstation, of I look the Description of a Stock, it has a tab about margins, and lists the initial and maintenance margin requirements for long and short positions - see screenshot attached. I'd like to get the same information via the TWS API in python. When requesting the contract details via the API, this information is not contained in the returned ContractDetails object. Here's a sample code using the ib_async wrapper: qqq = Stock(symbol='META', exchange='SMART', currency='USD') qqq_details = ib.reqContractDetails(qqq) pprint(qqq_details) here's the result of the printout: [ContractDetails(contract=Contract(secType='STK', conId=107113386, symbol='META', exchange='SMART', primaryExchange='NASDAQ', currency='USD', localSymbol='META', tradingClass='NMS'), marketName='NMS', minTick=0.01, orderTypes='ACTIVETIM,AD,ADJUST,ALERT,ALGO ,ALLOC,AON,AVGCOST,BASKET,BENC HPX,CASHQTY,COND,CONDORDER,DAR KONLY,DARKPOLL,DAY,DEACT,DEACT DIS,DEACTEOD,DIS,DUR,GAT,GTC,G TD,GTT,HID,IBKRATS,ICE,IMB,IOC ,LIT,LMT,LOC,MIDPX,MIT,MKT,MOC ,MTL,NGCOMB,NODARK,NONALGO,OCA ,OPG,OPGREROUT,PEGBENCH,PEGMID ,POSTATS,POSTONLY,PREOPGRTH,PR ICECHK,REL,REL2MID,RELPCTOFS,R PI,RTH,SCALE,SCALEODD,SCALERST ,SIZECHK,SMARTSTG,SNAPMID,SNAP MKT,SNAPREL,STP,STPLMT,SWEEP,T RAIL,TRAILLIT,TRAILLMT,TRAILMI T,WHATIF', validExchanges='SMART,AMEX,NYSE,CBOE,PHLX,ISE, CHX,ARCA,NASDAQ,DRCTEDGE,BEX,B ATS,EDGEA,BYX,IEX,EDGX,FOXRIVE R,PEARL,NYSENAT,LTSE,MEMX,IBEO S,OVERNIGHT,TPLUS0,PSX', priceMagnifier=1, underConId=0, longName='META PLATFORMS INC-CLASS A', contractMonth='', industry='Communications', category='Internet', subcategory='Internet Content-Entmnt', timeZoneId='US/Eastern', tradingHours='20241016:0400-20241016:2000;20241017:0400-20241017:2000;20241018:0400-20241018:2000;20241019:CLOSED;20241020:CLOSED;20241021:0400-20241021:2000', liquidHours='20241016:0930-20241016:1600;20241017:0930-20241017:1600;20241018:0930-20241018:1600;20241019:CLOSED;20241020:CLOSED;20241021:0930-20241021:1600', evRule='', evMultiplier=0, mdSizeMultiplier=1, aggGroup=1, underSymbol='', underSecType='', marketRuleIds='26,26,26,26,26,26,26,26,26,26, 26,26,26,26,26,26,26,26,26,26, 26,26,26,26,26', secIdList=[TagValue(tag='ISIN', value='US30303M1027')], realExpirationDate='', lastTradeTime='', stockType='COMMON', minSize=0.0001, sizeIncrement=0.0001, suggestedSizeIncrement=100.0, cusip='', ratings='', descAppend='', bondType='', couponType='', callable=False, putable=False, coupon=0, convertible=False, maturity='', issueDate='', nextOptionDate='', nextOptionType='', nextOptionPartial=False, notes='')]
Розпочато Ákos Maróy @ · Останніх @
upper and lower limit 2
Hello all, I would like to set an upper and lower limit for selling stocks I hold. For example, let's say that I hold 120 shares of SMCI and the current price is 32.50. I would like to SELL those 120 shares if it reaches 34.71 OR if it went down and reached 31.20: SMCI-STK--0.0---SMART-Nasdaq-USD-----SELL-120-STP-34.71 SMCI-STK--0.0---SMART-Nasdaq-USD-----SELL-120-STP-31.2 The question is, if I only hold 120 shares, can I still do that since I sent 2 calls of 120 shares each (240 in total)? Will it be rejected with "you are trying to sell 240 SMCI shares but you only hold 120"? Thank you
Розпочато Danny @ · Останніх @
How to get position info in "points" 5
What is the most efficient way to get information about position including the fields below. - open time - open price - unrealized PnL Request "reqPositions" and "reqPositionsMulti" return these - reqId - account - contract - avgCost 1. Instead of average cost, how do I get price of the stock / option / future when position was opened? 2. How do I get time when it was open? 3. There is a separate request for PnL but even if I get PnL, there are some missing pieces, e.g. I can't calculate the range in points between open and current prices of the asset.
Розпочато Andy Sanders @ · Останніх @
Is there generic method to format contract for reqContractDetails 7
To get stock contract, it requires only 4 fields. Name = "SPY" Exchange = "SMART" SecType = "STK" Currency = "USD" For stock options, the 4 fields above + 3 more Right = "C" Strike = 650 LastTradeDateOrContractMonth = "20241231" When it comes to futures and futures options, it gets messy. For example, after reading couple of posts in this group, this is the contract definition that I used to subscribe to live data feed for ES futures. Of course, "SecType" = "FUT" and "Exchange" = "SMART" would be more appropriate but here we go. Name = "ES" Exchange = "CME" SecType = "IND" Currency = "USD" I have no idea why it has to be "IND" instead of "FUT" but somehow it worked for "reqMktData". Meanwhile, when I try to pass this to "reqContractDetails", I get "No security definition was found for the request". The same happens when I try to request contract details for futures options. The funny part is that I don't populate these parameters manually, I just request all open orders and positions, copy contract object from there and use it in reContractDetails but IB API returns "No security found" error for it. In other words, IB API returns INCORRECT data that can't be used to make other requests. Hence the question, Is there a map or table that clearly defines which security type and exchange need to be used with specific securities, e.g. if I have these assets, how do I create method that correctly populates properties for them, so I could use their contract definitions in other API calls, like reqMktData? SPY SPY call option ES futures ES futures call option EURUSD
Розпочато Andy Sanders @ · Останніх @
The difference between realtimebar vs reqHistoricalData with barSizeSetting = "5S" and keepUpToDate = True
Hi All, do you guys know what is the difference between realtimebar vs reqHistoricalData with barSizeSetting = "5S" and keepUpToDate = True? Thanks xb
Розпочато xb @
TWS API Stopped accepting incoming connections sometimes 2
TWS sometimes suddenly cannot connect, and it must be re-verified and logged in again to fix it. Belows are gateway logs happened before my connection failure today 2024-11-29 08:37:59.254 [EY] INFO [JTS-ushmdsServicePingS9-286] - Farm ushmds/NATIVE: Closing dormant connection type:HISTORICAL_DATA 2024-11-29 08:37:59.254 [EY] INFO [JTS-ushmdsServicePingS9-286] - Disconnecting cdc1.ibllc.com:4000 [disconnectDetails=DisconnectDetails[sessionID=9,endPoint=cdc1.ibllc.com:4000,reason=DISCONNECT_ON_INACTIVITY,cause=null,systemMessage=null,keepSocketOpen=false]]... 2024-11-29 08:37:59.254 [EY] INFO [JTS-ushmdsServicePingS9-286] - Socket closed. 2024-11-29 08:37:59.254 [EY] INFO [JTS-ushmdsServicePingS9-286] - SocketTracker[name=name=ushmds(cdc1.ibllc.com:4000),usesCcpConMan=false,lastReadTimestamp=1732869470298,lastReadDateTime=2024-11-29T08:37:50.298,lastFixSendTime=]. 2024-11-29 08:37:59.254 [EY] INFO [JTS-ushmdsServicePingS9-286] - Interrupting dispatcher [sessionID=9]... 2024-11-29 08:37:59.254 [EY] INFO [JTS-ushmdsServicePingS9-286] - Interrupting listener [sessionID=9,disconnectSocket=true]... 2024-11-29 08:37:59.254 [EY] INFO [JTS-ushmdsServicePingS9-286] - AuthTimeoutMonitor-ushmds: deactivate 2024-11-29 08:37:59.254 [EY] INFO [JTS-ushmdsDispatcherS9-282S9-283] - Dispatcher thread terminating [sessionID=9,interrupted=true]... 2024-11-29 08:37:59.254 [EY] INFO [JTS-ushmdsListenerS9-281] - Socket or stream for connection cdc1.ibllc.com:4000 was closed by another thread. 2024-11-29 08:37:59.254 [EY] INFO [JTS-ushmdsServicePingS9-286] - Terminating ping thread 2024-11-29 08:37:59.254 [EY] INFO [JTS-ushmdsListenerS9-281] - Listener thread terminating [sessionID=9] [seen=36342294,totalShifted=36342294,moreAvailable=0] 2024-11-29 08:37:59.254 [EY] INFO [JTS-DisconnectedS9-551] - Farm ushmds/NATIVE: Lost active connection with disconnect status DISCONNECT_ON_INACTIVITY 2024-11-29 08:37:59.254 [EY] INFO [JTS-DisconnectedS9-551] - Farm ushmds/NATIVE: Not resetting 2024-11-29 08:37:59.255 [EY] INFO [JTS-AsyncNonLocked-33] - [50:176:176:1:0:4:2:DET] Sending error. 2024-11-29 08:37:59.255 [EY] INFO [JTS-AsyncNonLocked-33] - [50:176:176:1:0:4:2:DET] [4;2;-1;2107;HMDS data farm connection is inactive but should be available upon demand.ushmds;] 2024-11-29 08:37:59.255 [EY] INFO [JTS-AsyncNonLocked-33] - [50:176:176:1:0:4:2:DET] Error sent. 2024-11-29 08:38:31.130 [EY] INFO [JTS-CCPPingS2-28] - Resetting long time mode 2024-11-29 08:39:32.134 [EY] INFO [JTS-CCPPingS2-28] - Resetting long time mode 2024-11-29 08:40:11.939 [EY] INFO [JTS-DeadlockMonitor-2] - Memory:total=786,432KB free=277,852KB HeapUsage: Max=786,432KB used=506,764KB committed=786,432KB NonHeapUsage: Max=0KB used=172,722KB committed=176,432KB 2024-11-29 08:40:12.940 [EY] INFO [JTS-DeadlockMonitor-2] - CPU:cur=12.52% avg=0.38% 30 min avg=4.46% 10 min avg=12.51% 5 min avg=12.50% 1 min avg=12.52% GC:called=953 times CPU used=0.03% Finalizer:cur=0.00% avg=0.00% 30 min avg=0.00% 10 min avg=0.00% 5 min avg=0.00% 1 min avg=0.00% Threads Count:curr live=72 curr daemon=33 2024-11-29 08:40:33.139 [EY] INFO [JTS-CCPPingS2-28] - Resetting long time mode 2024-11-29 08:41:34.144 [EY] INFO [JTS-CCPPingS2-28] - Resetting long time mode 2024-11-29 08:42:35.148 [EY] INFO [JTS-CCPPingS2-28] - Resetting long time mode 2024-11-29 08:43:36.153 [EY] INFO [JTS-CCPPingS2-28] - Resetting long time mode 2024-11-29 08:44:37.158 [EY] INFO [JTS-CCPPingS2-28] - Resetting long time mode 2024-11-29 08:45:11.944 [EY] INFO [JTS-DeadlockMonitor-2] - Memory:total=786,432KB free=273,763KB HeapUsage: Max=786,432KB used=510,860KB committed=786,432KB NonHeapUsage: Max=0KB used=172,732KB committed=176,432KB 2024-11-29 08:45:12.945 [EY] INFO [JTS-DeadlockMonitor-2] - CPU:cur=12.52% avg=0.49% 30 min avg=6.54% 10 min avg=12.51% 5 min avg=12.51% 1 min avg=12.52% GC:called=953 times CPU used=0.03% Finalizer:cur=0.00% avg=0.00% 30 min avg=0.00% 10 min avg=0.00% 5 min avg=0.00% 1 min avg=0.00% Threads Count:curr live=72 curr daemon=33 2024-11-29 08:45:38.162 [EY] INFO [JTS-CCPPingS2-28] - Resetting long time mode 2024
Розпочато xb @ · Останніх @
No real-time data after IB nightly server reset 17
I have been using IB Gateway (v10.19.2o) inside a docker container. After the nightly reset of IB servers at around 0430 UTC, I get the following message on some days: Connectivity between IB and Trader Workstation has been restored - data maintained. The following farms are connected: eufarm; euhmds; secdefeu. The following farms are not connected: ushmds. Error Code: 1102 After this I don't receive any real-time data even if I resubscribe to it using reqRealTimeBars. I have tried resetting the data connection as well as account & the reset seems to be done fine but I still can't get the data. The only way to get the data is to re-login which requires 2FA. Curiously, on some days it just works fine after the nightly reset. In such cases, I get the following message (same error code as before but all farms are connected including ushmds): Connectivity between IBKR and Trader Workstation has been restored - data maintained. All data farms are connected: eufarm; euhmds; ushmds; secdefeu. Error Code: 1102 I was wondering if anyone else has also encountered this problem & found a solution for it that doesn't require re-login. Thanks, Farhan
Розпочато farhanferoz@... @ · Останніх @
Best practice for cancelmktdata 5
Hello I am currently have this in a foreach loop using if (hasCompleteData || hasPartialData) { ClientSocket.cancelMktData(cancelTickerId); MaxSubscriptioncancelledTickerIds.Add(cancelTickerId); logBuilder.AppendLine(hasCompleteData ? $"Max Subscription Data Cancel. Complete Data. Ticker Id: {cancelTickerId}" : $"Max Subscription Data Cancel. Partial Data. Ticker Id: {cancelTickerId}"); return true; // Ticker was successfully canceled My question is should i add sleep between each canceltickerid, I am batching about 300 canceltickerids at once and the tick call backs for each canceltickerids keeps firing, On the log for example I could call canclemktdata for a specific tickerid and for up to 2 minutes I may still get tick call backs for that partciular tickerid, Will adding sleep allow for faster processing or should i do smaller batches?
Розпочато H Liu @ · Останніх @
using EWrapper::fundamentalData 3
Hello everybody, is there anyone that use the EWrapper::fundamentalData function instead of the EClient::reqFundamentalData. The 2nd is deprecated and I should need more fundamental data, so I'd like to use the 1st but I can't find any documentation or example (in any programming language). Thank you in advance
Розпочато paolo.menghi@... @ · Останніх @
execDetails(...)+commissionReport(...) Callback different behaviour when not opening trade history 11
Hi all, i noticed a difference in the behaviour of the execDetails(...)+commissionReport(...) Callback functions. When i start the tws and do not open the "trade history" dialog then all orders that are opened or closed from this point are only "returned" ONCE in the execDetails(...) + commissionReport(...). Furthermore i do not receive the previous trading history ( more precise all executions and commission reports that occured before the new start of tws). If i open the dialog shortly after the start of the tws i receive all the executions and it keeps sending them in a regular time intervall. The reason why i am asking ( or created a topic), is that my trading system gets invalidated if i dont receive all the execution (i cant determined when a position is closed and the is no other way with this design). The problem is that the tws is restarting every day, so i get this set of conditions (after restart -> the dialog hasn't been opened, without intervening) and thus the callbacks are sending only once. Is it possible that a message is lost ( due to connection problems) ? If so, is there some mechanism to get the dialog open automatically ? Or how can i enforce it that the callbacks are sending periodically ? How is this solved in the IB Gateway ? regards, Simon
Розпочато simon.meier1987@... @ · Останніх @
API call: Error validating request.-'bF' : cause - Please enter a stop price 5
Hello all, I am sending 2 STP API calls (to sell at a specific increase and decrease from the current price, whichever reaches first), but I am getting an error message regarding "enter a stop price". What am I doing wrong? (and what is "bF"?) Thanks From the API log: SMCI-STK--0.0---SMART-Nasdaq-USD-----SELL-120-STP-34.71 SMCI-STK--0.0---SMART-Nasdaq-USD-----SELL-120-STP-31.2 getting: Error validating request.-'bF' : cause - Please enter a stop price Error validating request.-'bF' : cause - Please enter a stop price
Розпочато Danny @ · Останніх @
Documentation for OrderCancel? ... 3
Using C# API Version 10.30.01. Only a few weeks into using this API and have noticed the documentation is severely lacking in all areas (which seems to be the state of the programming world these days). Regardless, I needed to use the cancelOrder method. The deprecated documentation shows an example of the cancelOrder method as: client.cancelOrder(nextOrderId - 1, ""); The current documentation shows the same example as above. However, the code (downloaded) from IB contains an EClient.cancelOrder method with the following arguments: public void cancelOrder(int orderId, OrderCancel orderCancel) The code downloaded from IB shows the default constructor for an "OrderCancel" object as: public OrderCancel() { ManualOrderCancelTime = EMPTY_STR; ExtOperator = EMPTY_STR; ExternalUserId = EMPTY_STR; ManualOrderIndicator = int.MaxValue; } I ended up calling the cancelOrder method as follows, which works ... cancelOrder( order_id, new IBApi.OrderCancel() ); But I am ASSUMING this is OK as I do not receive any errors. If someone knows of a resource that fully describes the "OrderCancel" object, please post a link. Also, any ideas as to how often the documentation is actually updated? Thanks in advance.
Розпочато bdcoder @ · Останніх @
C# code needed to download earnings date data in a CSV
Hi I'm new to IB API and my coding skills are quite limited. I need someone to help me with my request. I am willing to pay for it if needed. If you are looking for payment then please reply to me privately at below email address with your proposed fee: mannyr4022@... I need a complete C# code that will contact the IB server, get the data I need, and perform error handling to handle issues. All I need to do is run the code. The data I need is the following in a CSV format: 1. Symbol 2. Day of earning announcement (actual day not proposed or tentative) 3. Time of announcement of date from item 2 4. Actual EPS 5. Forecasted EPS for the item 4 6. Next scheduled date for earning announcement Note: 1. Limit results to US listed securities only. 2. Include time zone if possible. 3. If IB provides item 2 and 3 as one field then just report that. I can parse the field to get the day and time. 4. One CSV file is produced for each symbol so if there are 5000 symbols then there are 5000 CSV files. 5. Add a variable that let's me indicate the folder where the CSV files are to be stored on my local machine. 6. Be extremely generous in your code comments so every detail is explained. 7. I will not download libraries, DLLs, third party software etc for security purposes so provide your code in plain text format so I can review the code before running it. It is ok to use IB libraries and any libraries that come with C#. 8. Retrieve all data for a given symbol. I'm not sure how far back IB data goes so go as far as back as possible. 9. If payment is involved, then payment is made after I have tested the code. I can wait a few weeks for the deliverable after scope and any other details have been finalized. Any questions please ask. Thank you
Розпочато AJ @
timeout when connecting to TWS Gateway, but existing connection still works 4
Hi, I found this interesting phenomenon today when trying to connect with a second client to a running TWS Gateway, that I'm getting a timeout error. At the same time, the gateway has an active connection running by a client, that still is operational and works. Of course the new connection is using a different client id than the existing one. In all cases the connection is made to 127.0.0.1, to the same port 4002. I can telnet to this port and it opens up, so the Gateway is listening on the port. But a new client can't connect and gets a timeout. What could cause this issue? Ákos
Розпочато Ákos Maróy @ · Останніх @
keeping subscriptions 5
Hi Group, For quite some time I observe that some data subscriptions do not hold overnight. Most of them are streaming Level I tick data. My routine includes daily restart at 5PM EST, this is when all market data subscriptions are started. Stock symbols pause trading at 8PM EST, and remain idle until IB restart at around 1-2AM EST. Everything runs smooth for most symbols during all the reconnections, but for some symbols. Usually what happens, a few symbols just fail to acquire data starting at 4AM EST unless I restart again. The weird part is that they are different symbols each time, and there're no errors logged whatsoever. Again no changes to data subscriptions are made from the start at 5PM until 4AM when ETH starts trading. Just some subscriptions do not remain it seems. This is quite difficult to catch, as many symbols do not open legitimately at 4AM as there're no quotes or trades. But this shouldn't happen to actively traded symbols. No data lines limits are breached. Where should I look to see why this happens?
Розпочато bespalex @ · Останніх @
fx about EUR.USD 3
anyone know which exchange IB is trading for EUR.USD? and for fx data, it is trading 24/5, so if i look at the daily data, what is the time point IB defines the Open and Close price? i tried to use mycontract = Contract() mycontract.symbol = "EUR" mycontract.secType = "CASH" mycontract.exchange = "IDEALPRO" mycontract.currency = "USD" whatToShow='BID' but cannot find the volume data, do i need to pay? i am using simulation account. thanks!
Розпочато alan chau @ · Останніх @
anyone know where I can find the IB maintenance timetable 4
All this week I have had a cronjob running a script to get 3 years of daily trades from ib using reqHistoricalData . Nothing special, just running download speed tests for something else. The cronjob ran successfully at 18:00 cst monday through thursday but this friday 11/15/24 it failed consistantly and all I got was ERROR - Attempting to connect, attempt 1 of 10
Розпочато comicpilsen @ · Останніх @
Is it prohbited to share my own positions/orders on social media ? 2
Hello, Is it prohbited to share my own positions/orders on social media ? of course I made a disclaimer but I don't know if the US/European regulation or CME Group prohbited it ? Can somewone answer please ? Thanks
Розпочато zzitounti@... @ · Останніх @
Current Image
Image Name
Sat 8:39am