utilmon / EasyIB

Python wrapper for Interactive Brokers Client Portal Web API
BSD 3-Clause "New" or "Revised" License
89 stars 24 forks source link

how to get futures data and place orders #3

Closed spitzbubchen closed 3 years ago

spitzbubchen commented 3 years ago

As I mainly trade futures I am wondering how to get futures data and place orders? Doing the following:

bars = ib.get_bars("NG", period="1w", bar="1d")
print(bars)

Results in the following error:

{'error': "No data of type EODChart is available for the exchange 'VALUE' and the security type 'Stock' and '1 W' and '1 day'"}

Using ibapi the sequence would go something like this:

contract = Contract()
contract.symbol = 'NG'
contract.exchange = 'NYMEX'
# contract.secType = 'CONTFUT'
contract.secType = 'FUT'
contract.lastTradeDateOrContractMonth  = '202109'

app.reqHistoricalData(1, contract, '20210815 17:59:00', '10 D', '15 mins', 'BID', 0, 2, False, [])

How would this be done using EasyIB?

utilmon commented 3 years ago

I don't get your error message on my end. However, get_bars and get_conid assumes the security is a stock, thus it returns Novagold stock prices. This is because a future security can have multiple contract id's due to multiple expiration dates.

I just updated the package such that you can put an optional argument conid in get_bars. This should solve your problem as long as you have conid. The conid can be found by curl -X GET "https://localhost:5000/v1/api/trsrv/futures?symbols=NG" -k, or you can use requests python package to interact with REST API.

utilmon commented 3 years ago

I just added another function get_fut_conids() to retrieve a list of contract id objects. Please try in case you are still having a problem. I will close this ticket.

spitzbubchen commented 3 years ago

Thanks! Sorry for the late reply. I was away for awhile.

It is nice to able to grab the current contract from the top of the contract id list as contract = ib.get_fut_conids('NG')[0]. I can also confirm that I can now buy and sell future contracts.

I would like to suggest adding the conid to the get_portfolio function as this makes it easy to quickly buy or sell exisitng contracts. Maybe modify the code as;

        dic = {}
        for item in response.json():
            dic.update({item["contractDesc"]: {"conid": item["conid"], "position": item["position"]} })
        dic.update({"USD": self.get_cash()})  # Cash balance