简体   繁体   中英

Problem with IB Insync Futures Order on Interactive Brokers TWS API

I am hoping somebody here may be able to help clarify how to structure the IB-Insync Contract Format for a Futures order in a python API link with Interactive Brokers API. I am trying to develop a autobot API link into the Interactive Brokers API using IB-Insync. I have the system working perfectly now automatically placing orders with a 'Stock' contract format; as follows:

stock = Stock(message_data['ticker'], 'SMART', 'USD')
ib.qualifyContracts(stock)
order = MarketOrder(message_data['strategy']['order_action'], message_data['strategy']['order_contracts'])
trade = ib.placeOrder(stock, order)

but when i apply the same python script to my understanding of the required IB-Insync contract format for a Futures order as per the documentation, nothing happens and a error shows in the API log.

The IB-Insync Futures contract format used is below:

contract = Future(symbol='MES', lastTradeDateOrContractMonth='20211217', exchange='GLOBEX',
localSymbol='MESZ1', multiplier='5', currency='USD')
ib.qualifyContracts(contract)
order = MarketOrder(message_data['strategy']['order_action'], message_data['strategy']['order_contracts'])
trade = ib.placeOrder(contract, order)

API Log Error message below:

22:28:49:791 <- 9-8-59-0-MES-STK--0.0---SMART--USD---0--- 22:28:50:029 -> ---A4-2-59-200-No security definition has been found for the request- 22:28:50:030 <- 3-60-0-MES-STK--0.0---SMART--USD-----BUY-1-MKT------O-0--1-0-0-0-0-0-0-0--0.0--------0---1-0---0---0-0--0------0-----0-----------0---0-0---0--0-0-0-0-------0---------0-0-0-0- 22:28:50:264 -> ---A4-2-60-200-No security definition has been found for the request-

I have tried numerous different ways to structure the Futures Contract Format; including:

contract=Future('MES', '20121217', 'GLOBEX')

But the same problem occurs - the Interactive Brokers TWS API is recording the order as a STK order routing it through the SMART exchange protocol; which clearly it is not. I can manually place a Futures order on TWS for MES; so it cannot be due to a privilege's setting.

I am hoping somebody here may know of a resolution or has come across this problem before?

I am stumped by it

Thankyou for your help

The entire code is below:

import redis, json
from ib_insync import *
import asyncio, time, random
from dataclasses import dataclass, field
from typing import List, NamedTuple, Optional
import ib_insync.util as util

# connect to Interactive Brokers 
util.startLoop()
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)

# connect to Redis and subscribe to tradingview messages
r = redis.Redis(host='localhost', port=6379, db=0)
p = r.pubsub()
p.subscribe('tradingview')

async def check_messages():
    print(f"{time.time()} - checking for tradingview webhook messages")
    message = p.get_message()
    if message is not None and message['type'] == 'message':
        print(message)

        message_data = json.loads(message['data'])

        contract = Future(symbol='MES', lastTradeDateOrContractMonth='20211217', exchange='GLOBEX', localSymbol='MESZ1', multiplier='5', currency='USD')
        ib.qualifyContracts(contract)
        order = MarketOrder(message_data['strategy']['order_action'], message_data['strategy']['order_contracts'])
        trade = ib.placeOrder(contract, order)

async def run_periodically(interval, periodic_function):
    while True:
        await asyncio.gather(asyncio.sleep(interval), periodic_function())

asyncio.run(run_periodically(1, check_messages))

ib.run()

Thankyou to those who have answered - after extensive research, experimentation, and an idea from another forum.... i found the solution.

The Contract Parameter format for a Futures order in IB-Insync is very different to that which can be used in a Stock order.

the code that finally worked is:

        fut_contract = Contract()
        fut_contract.secType = 'FUT'
        fut_contract.exchange = 'GLOBEX'
        fut_contract.currency = 'USD'
        fut_contract.symbol = 'MNQ'
        fut_contract.localSymbol = 'MNQZ1'
        ib.qualifyContracts(fut_contract)
        
        order = MarketOrder('order_action', 'order_contracts')
        trade = ib.placeOrder(fut_contract, order)

The contract parameter format for a Stock order is as simple as:

stock = Stock(MSFT, 'SMART', 'USD')
ib.qualifyContracts(stock)
order = MarketOrder('BUY/SELL', Qty)
trade = ib.placeOrder(stock, order)

As far as i am concerned - this required format is not clearly communicated in the IB-Insync documentation, or maybe because i am self taught programmer it wasn't blatantly obvious to me- but might be to seasoned developers. Anyway - hope this info helps somebody when they become stuck on the same problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM