¿ªÔÆÌåÓý

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

Re: Error: 1 321 Error validating request.-'bW' : cause - Please enter a local symbol or an expiry

 

Oscar,

what is it that you don't understand? Did you read the API documentation, especially the chapters I pointed you to?

We'd be happy to help you understand how TWS API works, but the group cannot fix large chunks of your code or teach you basic Python programming skills by email. Also, I don't work with Python and neither does the majority or our 6,000 members.

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

On Mon, Nov 21, 2022 at 07:15 PM, Oscar Castillo wrote:

I'm sorry but I still don't understand. I've included my code, if you wouldn't mind taking a look. It's copied from a book, "Algorithmic Trading with Interactive Brokers."
?


Re: Error: 1 321 Error validating request.-'bW' : cause - Please enter a local symbol or an expiry

 

The exchange is now CME
Globes doesn¡¯t work anymore

On Sun, Mar 13, 2022 at 6:51 PM comicpilsen <comicpilsen@...> wrote:

I want to get continuous futures and don't want to mess around with expiration et al. Basically what I see in the TWS watchlist.

I tried

reqMktData 

with 
Symbol  = "ES"
Exchange = "GLOBEX"
Currency = "USD"

and got the error in the subject line. Is there ANY variant of reqMktData that might work OR do I have to resort to reqRealTimeBars and pick the last bar?

No point in posting code as I am writing in julia. The calls to the TWS api are populated the same so ANY help would be appreciated.

thanks

and got the error in the subject line.


Re: Error: 1 321 Error validating request.-'bW' : cause - Please enter a local symbol or an expiry

 

Hello again Jurgen,

I'm sorry but I still don't understand. I've included my code, if you wouldn't mind taking a look. It's copied from a book, "Algorithmic Trading with Interactive Brokers."

Thank you again for your time and?help.

Sincerely,
Oscar


''' Reads continuous futures contracts '''

from datetime import datetime, timedelta
from threading import Thread
import os
import time
import pandas as pd
import shutil

from ibapi.client import EClient, Contract
from ibapi.wrapper import EWrapper
from ibapi.utils import iswrapper

class ReadFutures(EWrapper, EClient):
? ? ''' Serves as the client and the wrapper '''

? ? def __init__(self, addr, port, client_id):
? ? ? ? EClient.__init__(self, self)

? ? ? ? # Initialize properties
? ? ? ? self.local_symbol = None
? ? ? ? self.multiplier = None
? ? ? ? self.symbols = {'EUR':'CME', 'ES':'CME', 'CHF':'CME', 'GBP':'CME',
? ? ? ? ? ? 'CAD':'CME'}
? ? ? ? self.price_dict = {}

? ? ? ? # Connect to TWS
? ? ? ? self.connect(addr, port, client_id)

? ? ? ? # Launch the client thread
? ? ? ? thread = Thread(target=self.run)
? ? ? ? thread.start()

? ? @iswrapper
? ? def contractDetails(self, req_id, details):
? ? ? ? ''' Called in response to reqContractDetails '''

? ? ? ? # Obtain data for the contract
? ? ? ? self.local_symbol = details.contract.localSymbol
? ? ? ? self.multiplier = details.contract.multiplier

? ? @iswrapper
? ? def historicalData(self, req_id, bar):
? ? ? ? ''' Called in response to reqHistoricalData '''

? ? ? ? # Add the futures prices to the dictionary
? ? ? ? self.price_dict['CLOSE'].append(bar.close)
? ? ? ? self.price_dict['LOW'].append(bar.low)
? ? ? ? self.price_dict['HIGH'].append(bar.high)
? ? ? ? self.price_dict['VOL'].append(bar.volume)

? ? def error(self, req_id, code, msg):
? ? ? ? print('Error {}: {}'.format(code, msg))

def main():

? ? # Create the client and connect to TWS
? ? client = ReadFutures('127.0.0.1', 7497, 0)

? ? # Get expiration dates for contracts
? ? for symbol in client.symbols:

? ? ? ? # Define contract of interest
? ? ? ? con = Contract()
? ? ? ? con.symbol = symbol
? ? ? ? con.secType = "CONTFUT"
? ? ? ? con.exchange = client.symbols[symbol]
? ? ? ? con.currency = "USD"
? ? ? ? con.includeExpired = True
? ? ? ? client.reqContractDetails(0, con)
? ? ? ? time.sleep(1)

? ? ? ? # Request historical data for each contract
? ? ? ? if client.local_symbol:

? ? ? ? ? ? # Initialize price dict
? ? ? ? ? ? for v in ['CLOSE', 'LOW', 'HIGH', 'VOL']:
? ? ? ? ? ? ? ? client.price_dict[v] = []

? ? ? ? ? ? # Set additional contract data
? ? ? ? ? ? con.localSymbol = client.local_symbol
? ? ? ? ? ? con.multiplier = client.multiplier

? ? ? ? ? ? # Request historical data
? ? ? ? ? ? end_date = datetime.today().date() - timedelta(days=1)
? ? ? ? ? ? client.reqHistoricalData(1, con, end_date.strftime("%Y%m%d %H:%M:%S"),
? ? ? ? ? ? ? ? '1 D', '1 min', 'TRADES', 1, 1, True, [])
? ? ? ? ? ? time.sleep(1)

? ? ? ? ? ? # Write data to a CSV file
? ? ? ? ? ? if client.price_dict['CLOSE']:
? ? ? ? ? ? ? ? df = pd.DataFrame(data=client.price_dict)
? ? ? ? ? ? ? ? #df.to_csv(symbol + '.csv', encoding='utf-8', index=False)
? ? ? ? ? ? ? ? #client.price_dict.clear()
? ? ? ? ? ? ? ? print (df)
? ? ? ? else:
? ? ? ? ? ? print('Could not access contract data')
? ? ? ? ? ? exit()

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

if __name__ == '__main__':
? ? main()?

On Sun, Nov 20, 2022 at 9:44 PM ´³¨¹°ù²µ±ð²Ô Reinold via <TwsApiOnGroupsIo=[email protected]> wrote:

If you have not done so yet, take a look at the especially the chapters on and . The documentation has snippets of code in various programming languages.

The workflow is quite simple:

  • You create a contract object and initialize the fields , , and , for example, with values "ES", "CONTFUT", and "CME"
  • You call and pass that contract object
  • TWS API returns a list of objects for your query and delivers each object with a separate call of your method. The end of the list is indicated with a call of your method. For a CONTFUT query you should expect one callback of and each.
  • The object you receive contains, among other items, a fully populated object for, in our example and today, ESZ2. You can pass that object to any and all TWS API requests that expect a contract object parameter. You can change for that contract to "FUT" but we never found that necessary.
´³¨¹°ù²µ±ð²Ô

On Sun, Nov 20, 2022 at 07:35 PM, <ungaboscar@...> wrote:
?I am a newbie to TWS API and Python both, so I appreciate your time and patience.

?I don't completely understand the work flow you outlined for using CONTFUT with real time data. Could you write it out in more detail in Python?


Re: Error: 1 321 Error validating request.-'bW' : cause - Please enter a local symbol or an expiry

 
Edited

If you have not done so yet, take a look at the especially the chapters on and . The documentation has snippets of code in various programming languages.

The workflow is quite simple:

  • You create a contract object and initialize the fields , , and , for example, with values "ES", "CONTFUT", and "CME"
  • You call and pass that contract object
  • TWS API returns a list of objects for your query and delivers each object with a separate call of your method. The end of the list is indicated with a call of your method. For a CONTFUT query you should expect one callback of and each.
  • The? object you receive contains, among other items, a fully populated object for, in our example and today, ESZ2. You can pass that object to any and all TWS API requests that expect a contract object parameter. You can change for that contract to "FUT" but we never found that necessary.
´³¨¹°ù²µ±ð²Ô


On Sun, Nov 20, 2022 at 07:35 PM, <ungaboscar@...> wrote:
?I am a newbie to TWS API and Python both, so I appreciate your time and patience.

?I don't completely understand the work flow you outlined for using CONTFUT with real time data. Could you write it out in more detail in Python?


Re: Error: 1 321 Error validating request.-'bW' : cause - Please enter a local symbol or an expiry

 

Hello Jurgen,

This is my first time asking a question to this forum. I know this thread is months old but I encountered the same issue today. I am a newbie to TWS API and Python both, so I appreciate your time and patience.

?I don't completely understand the work flow you outlined for using CONTFUT with real time data. Could you write it out in more detail in Python?

Thank you in advance.

Cordially,
Oscar


Re: order not getting filled during earnings

 

On Wed, Nov 16, 2022 at 04:16 PM, ´³¨¹°ù²µ±ð²Ô Reinold wrote:
´³¨¹°ù²µ±ð²Ô
Hi ´³¨¹°ù²µ±ð²Ô, Here is what I do: 3-4 minutes before the earnings, I place a basic StopLimit order through the API. I see the orders and status shows dark blue color, in the TWS gui
So once the trigger price is attained, some of the orders get filled, which get executed as limit or better. So it does work sometimes.
But sometimes when there is sudden price change, I see the color change to green but order is not filled.?
Even worse is after a minute or so, the stock reverses and guess what it gets filled going in the wrong direction putting me in negative P/L.
This happened today with PANW. My order had about a dollar difference between the stop price and the limit price. Is this too narrow?
For some reason the tickbytick data file did not get saved. But the problem has nothing to do with the streaming data I receive.
I did not receive any error callback. OutsideRTH is set to true. It did work for AMAT.
Thanks so much
sam


Re: C++ upgrade api to 10.11, __bid64.. error

 

I had the same problem, and resolved it by changing platform from x64 to win32.


Re: order not getting filled during earnings

 
Edited

First of all, TickByTick data is not aggregated. For TickByTickLast, for example, you will get one callback for every trade that takes place. And while some members have reported that callbacks appear to be "bunched" together, that usually is identified as a local or ISP network buffering issue. The only time we experience "bunching" (for ES futures) is when an order for, say, 250 contracts is quickly filled by a large number of small trades with 1 to 50 contracts adding up to 250. Each of these small trades is reported individually with only microseconds of time between them.

I don't think we have enough information to effectively help you with the order not getting filed issue. Do you place the order via the API and monitor it with TWS? The best I can do is give you a list of things I would check in these cases:
  • Does your client log show any OrderStatus or OrderState callbacks or errors from IBKR that could give you more insight?
  • I assume we are talking about a point in time that is after the regular trading hours. Are you sure your order has OutsideRTH and possibly ConditionsIgnoreRth set to true?
  • The instruments you mention are listed on several different exchanges. Have you selected a specific exchange where the STPLMT order might be executed natively at the exchange, or do you use some IBKR features that make the order one that is simulated at IBKR? For simulated orders you can select one of several trigger methods in the order object.
  • There are to flag orders, and apparently since TWS 919 "native stops at the exchange, both triggered and untriggered, display green". I'd look for an additional indication that the order is definitely triggered but not filled.
  • orders have two prices that impact whether the order can get filled. Assuming the stop trigger price was "attained or penetrated" and IBKR or the exchange placed the limit order for you, was your limit price selected so that the order could "buy or sell at a specified price or better"? Or was the price for the instrument on the "worse price" side by the time the limit order was in place?
Hope anything of this helps.
´³¨¹°ù²µ±ð²Ô


On Tue, Nov 15, 2022 at 02:21 PM, @sv624 wrote:
Hi,?
I place a StopLimit order before earnings release. The stock drops 10% but my order does not get executed.
I see the color change to green as soon as the price dropped. But why does it not execute?
I guess too quick price change and not enough liquidity? But this happened with major tickers like META, AMZN etc.
Too narrow trigger price and limit price? I tried increasing it but did not help.
I subscribed to tick by tick data. When the price drops suddenly, I don't see any ticks during some part of the drop.
If IBKR tick by tick is aggregate of 300ms as I read in some posts, then is this a limitation of IBKR?
Thank you


Re: order not getting filled during earnings

 

Simple price condition triggering a limit order would do unless you're using some sort of STP LMT that sits on the exchange.


Re: order not getting filled during earnings

 

No, I have not tried conditional, what would be the condition? There was no halt.


Re: order not getting filled during earnings

 

Have you tried using conditional orders instead? Are you certain there isn't a volatility halt in place?


order not getting filled during earnings

 

Hi,?
I place a StopLimit order before earnings release. The stock drops 10% but my order does not get executed.
I see the color change to green as soon as the price dropped. But why does it not execute?
I guess too quick price change and not enough liquidity? But this happened with major tickers like META, AMZN etc.
Too narrow trigger price and limit price? I tried increasing it but did not help.
I subscribed to tick by tick data. When the price drops suddenly, I don't see any ticks during some part of the drop.
If IBKR tick by tick is aggregate of 300ms as I read in some posts, then is this a limitation of IBKR?
Thank you


Re: Subscribe to Futures Quotes ES Contract

 

[I spent the time and effort to write this reply to a message that since has been deleted. Please DO NOT delete messages. Current and future readers will not be able to easily follow the discussion in that post when messages are missing.]

All API requests that require a contract as one of the parameters will be impacted by this exchange name change, not just market data requests. But this change has really nothing to do with the API itself (though it obviously makes your clients fail). It is a change in instrument data and as such not much different from cases where instruments get relisted at a different exchanges, when an exchange modifies the ticker symbol for an instrument, or when contracts change as a result of mergers, acquisitions, or divestitures. How would you generally learn about those event?

I don't think that there is one or even could be a single place where you can read up on any and all major changes IBKR makes. In this specific case:

  • We received an email on October 28 and I assume other clients who have recently traded GLOBEX instruments did so, too. I made a post about it the same day to alert group members: Update and Consolidation of Exchange Names (GLOBEX, CMECRYPTO, ECBOT, NYMEX)
  • The TWS API documentation changed over a month ago as you can see in the and examples that used ES/GLOBEX have been changed to ES/CME.
  • And I am sure there were other trader focused announcements, but I don't generally get or read those.

There are steps you can take to harden the solution and make it more fault tolerant. For example, as a matter of best practice, we never create contract objects for any request manually. We rather make a query when the client starts (or at least once a day for clients that run for extended periods of time).

In this case the query would uniquely identify the instruments with a query such as ESZ2:FUTURE:GLOBEX:ES in the past and ESZ2:FUTURE:ES:CME now. You could also make a more generic query that, for example, returns all currently active ES contract objects. In any case, we use the contract object that IBKR has filled out completely before it is returned to us.

Such an approach has several significant advantages in general and specifically for this case. Among them:

  • You centralize all instrument related error handling in one central point rather than exposing all subsystems with instrument related details (¡°separation of concerns¡±). So instead of a somewhat misleading "Market Data Request Error" or "Order Placement Error" much later in the life-cycle of your client, you get an early ¡°No Such Instrument Exists¡± error that is much easier to understand and debug.
  • Getting contract objects from queries has the added benefit that you receive up-to-date trading hour details for the next few days including short notice changes to the regular schedule in case of local holidays or emergencies.
  • And finally, IBKR tells you the native instrument time zone that comes in handy in all kinds of situations and specifically after the functional changes since TWS 10.17 where the ¡°local TWS time zone¡± approach is being deprecated.
And finally, you could have a small ¡°pre-flight check list¡± tool that exercises various API functions important to you when you restart TWS/IBGW and your clients after the weekend. This can be automated and would include among others:
  • connect to TWS/IBGW
  • perform requests for the instruments you trade most often to make sure the instruments exist
  • inspect the contract objects and alert in case of any unexpected changes (such as different trading schedules, unexpected market closure announcements, additional different primary exchange)
  • request market data for each of the contracts to make sure subscriptions are active
  • place ¡°WhatIf¡± orders for each of the contracts to make sure all trading permissions are active
Hope this helps,
´³¨¹°ù²µ±ð²Ô


Re: Subscribe to Futures Quotes ES Contract

 

If it happened today, change exchange name from globex to cme everywhere in your code and see if that?works. Ib made a change to their api today.


On Mon, Nov 14, 2022 at 3:41 PM Frank Bell via <fbell50=[email protected]> wrote:
I'm having the same problem with code even older than 10 years.

Virus-free.


Re: Subscribe to Futures Quotes ES Contract

 

I'm having the same problem with code even older than 10 years.

Virus-free.


Re: Subscribe to Futures Quotes ES Contract

 

Take a look at our post Update and Consolidation of Exchange Names (GLOBEX, CMECRYPTO, ECBOT, NYMEX)

IBKR changed the exchange name GLOBEX to CME over the last few weeks and ES/MES and others changed this weekend. Just replace "GLOBEX" with "CME".

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


On Mon, Nov 14, 2022 at 05:09 PM, <marluv@...> wrote:
Hello There,
This is a easy question.

This morning my legacy IBSDK from 10 years ago stopped working. I am not sure what IB did on their end but no more es futures data.

So I am upgrading to the latest build... Can someone help me populate these variables for the current ESZ2 contract... I am a bit rusty!! It's been years.
Thanks !!!


Re: Subscribe to Futures Quotes ES Contract

 

THIS IS HOW MY OLD CODE USE TO WORK :

?? ???? Contract??? ??? ??? ??? ??? ??? ? c_ES;
?? ???? c_ES.symbol??? ??? ??? ??? ??? ??? ? = "";??? ??? ??? ??? ??? //"MSFT";
?? ???? c_ES.secType??? ??? ??? ??? ??? ? = *SecType::FUT;??? ??? //"STK"
?? ???? c_ES.currency??? ??? ??? ??? ??? ? = "USD";
?? ???? c_ES.exchange??? ??? ??? ??? ??? ? = *Exchange::GLOBEX;??? //"SMART";
?? ???? c_ES.expiry??? ??? ??? ??? ??? ??? ? = "202212";
?? ???? c_ES.localSymbol??? ??? ??? ??? ? = "ESZ2";
?? ?
THEN I WOULD CALL
?? ???? TEST( 100, EC->reqMktData( INDEX_SNP, c_ES, "", false ) );

Do I use replace reqMktData with ? reqTickByTickData ???

HELP!!!


Subscribe to Futures Quotes ES Contract

 

Hello There,
This is a easy question.

This morning my legacy IBSDK from 10 years ago stopped working. I am not sure what IB did on their end but no more es futures data.

So I am upgrading to the latest build... Can someone help me populate these variables for the current ESZ2 contract... I am a bit rusty!! It's been years.
Thanks !!!

HELP!!

Contract ContractSamples::MY_ES_Contract() {
?? ?//! [futcontract_local_symbol]
?? ?Contract contract;
?? ?contract.secType = "FUT";
?? ?contract.exchange = "GLOBEX";
?? ?contract.currency = "USD";
?? ?contract.localSymbol = "ESZ2";
?? ?//! [futcontract_local_symbol]
?? ?return contract;
}


Re: Place few parellel Limit orders on a "cash" account, above the amount of cash the acount has

 

Confirmed this here:

On Mon, Nov 14, 2022 at 10:25 PM, buddy wrote:

OCA is not guaranteed


Re: Place few parellel Limit orders on a "cash" account, above the amount of cash the acount has

 

On Mon, Nov 14, 2022 at 05:41 PM, alon86 wrote:

When I have balance of 1,000$, I can submit two OCA orders of 500$ each. When I add the 3rd order - it cancels one of the first two.

I'm surprised this happens. My thought was you could add all four orders to one OCA group, since only one of the orders could ever get executed... perhaps even assigning all your BP to each order. Then, in the same light as Edward suggests, handle the "onFill" by resubmitting the remaining, cancelled orders (adjusted for buying power if desired) in a new OCA group; rinse, lather, repeat.

I guess it's possible that OCA is not guaranteed though. And, there's a small chance of getting more than one in the group filled. Then I could understand IB limiting the sum impact of the orders in the OCA group.

Interesting to know.