¿ªÔÆÌåÓý

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

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?

Join [email protected] to automatically receive all group messages.