Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
IBKR Purchasing code issue
#1
Good morning all,


I'm in the middle of getting a bit of code together to make multiple trades using the bag method, this is what I've come up with thus far and for the most part, it works, up until it gives me the ERROR 1 10268 The 'EtradeOnly' order attribute is not supported.


###code start ###

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract, ComboLeg
from ibapi.order import Order
from ibapi.tag_value import TagValue
from ibapi.common import OrderId

# Contract definitions
contracts = [
    {"conId": 120549942, "symbol": "AAPL", "secType": "CFD", "currency": "USD", "exchange": "NASDAQ"},
    {"conId": 131067756, "symbol": "TSLA", "secType": "STK", "currency": "USD", "exchange": "NASDAQ"},
    {"conId": 118239139, "symbol": "MSFT", "secType": "STK", "currency": "USD", "exchange": "NASDAQ"},
]

# Lookup dictionary
contract_lookup = {c["symbol"].upper(): c for c in contracts}

# Parse legs from text input
def parse_legs_from_text(text: str):
    legs = []
    for line in text.strip().splitlines():
        parts = line.split(",")
        if len(parts) != 4:
            raise ValueError(f"Invalid line format: {line}")
        symbol, action, ratio, exchange = [p.strip() for p in parts]
        symbol = symbol.upper()
        if symbol not in contract_lookup:
            raise ValueError(f"Unknown symbol: {symbol}")
        contract = contract_lookup[symbol]
        legs.append({
            "conId": contract["conId"],
            "symbol": symbol,
            "action": action.upper(),
            "ratio": int(ratio),
            "exchange": exchange.upper()
        })
    return legs

# Main IBKR app
class IBApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        self.next_order_id = None  # will be set via nextValidId

    # Automatically called by IBKR on connection
    def nextValidId(self, orderId: int):
        print(f"Next valid orderId: {orderId}")
        self.next_order_id = orderId
        # Optionally place your first order automatically here
        # self.place_example_order()

    # Place combo order
    def multipurchase(self, textbox_input: str, lmtPrice: float = 80, totalQuantity: int = 10):
        if self.next_order_id is None:
            print("Next order ID not yet received. Cannot place order.")
            return

        orderId = self.next_order_id
        self.next_order_id += 1  # increment for next order

        legs_input = parse_legs_from_text(textbox_input)

        # Build combo contract
        mycontract = Contract()
        mycontract.symbol = ",".join([leg["symbol"] for leg in legs_input])
        mycontract.secType = "BAG"
        mycontract.currency = "USD"
        mycontract.exchange = "SMART"

        mycontract.comboLegs = []
        for leg_data in legs_input:
            leg = ComboLeg()
            leg.conId = leg_data["conId"]
            leg.ratio = leg_data["ratio"]
            leg.action = leg_data["action"]
            leg.exchange = leg_data["exchange"]
            mycontract.comboLegs.append(leg)

        # Build order
        myorder = Order()
        myorder.orderId = orderId
        myorder.action = "BUY"
        myorder.orderType = "MKT"
        myorder.lmtPrice = lmtPrice
        myorder.totalQuantity = totalQuantity
        myorder.tif = "GTC"
     #   myorder.smartComboRoutingParams = [TagValue('NonGuaranteed', '1')]

        # Place the order
        self.placeOrder(orderId, mycontract, myorder)
        print(f"Placed combo order with orderId {orderId}")

    # Optional: IBKR callbacks
    def openOrder(self, orderId: OrderId, contract: Contract, order: Order, orderState):
        print(f"openOrder - orderId: {orderId}, contract: {contract.symbol}, action: {order.action}, qty: {order.totalQuantity}, price: {order.lmtPrice}")

    def orderStatus(self, orderId: OrderId, status: str, filled: float, remaining: float, avgFillPrice: float, permId: int, parentId: int, lastFillPrice: float, clientId: int, whyHeld: str, mktCapPrice: float):
        print(f"orderStatus - orderId: {orderId}, status: {status}, filled: {filled}, remaining: {remaining}, avgFillPrice: {avgFillPrice}")

    def execDetails(self, reqId: int, contract: Contract, execution):
        print(f"execDetails - reqId: {reqId}, contract: {contract.symbol}, executionId: {execution.execId}")

# ------------------- Usage -------------------

if __name__ == "__main__":
    app = IBApp()
    app.connect("127.0.0.1", 4002, clientId=1000)

    # Example combo order input
    textbox_input = """
    AAPL,BUY,1,SMART
    TSLA,SELL,1,SMART
    MSFT,BUY,2,SMART
    """

    # Wait until nextValidId arrives before placing orders
    import time
    import threading

    def place_order_when_ready():
        while app.next_order_id is None:
            time.sleep(0.1)
        app.multipurchase(textbox_input, lmtPrice=80, totalQuantity=10)

    threading.Thread(target=place_order_when_ready, daemon=True).start()

    app.run()


#code end#
So I'm not using the etradeonly attribute, any ideas? I've been stuck with this for a few days now and I'm not sure, I can't find anywhere else to ask.

Also I tried to put this in a code snippet and it wouldn't let me, the other buttons work; I wasn't sure what the correct attribute was to encapsulate it either.

Thanks

Comps
buran write Sep-23-2025, 11:33 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Updating Code And Having Issue With Keys Xileron 8 5,086 May-25-2023, 11:14 PM
Last Post: DigiGod
  NameError issue with daughter's newb code MrGonk 2 2,671 Sep-16-2021, 01:29 PM
Last Post: BashBedlam
  Calculator code issue using list kirt6405 4 4,004 Jun-11-2021, 10:13 PM
Last Post: topfox
  Issue with code for auto checkout nqk28703 2 3,592 Nov-01-2019, 09:33 AM
Last Post: nqk28703
  code issue sandy 1 2,687 Mar-14-2019, 07:16 PM
Last Post: micseydel
  Visual Studio Code - PEP8 Lambda Issue Qui_Ten 1 4,335 Jan-28-2019, 08:17 AM
Last Post: buran
  Wine / liquor dispenser project code issue onlinegill 0 3,067 Nov-20-2018, 10:41 PM
Last Post: onlinegill
  Issue using cv2.cv in code Huzefa95s 7 11,537 Oct-28-2018, 06:11 AM
Last Post: Huzefa95s
  Issue in my multiprocessing Python code? PrateekG 7 6,713 Jul-19-2018, 06:47 PM
Last Post: gontajones
  Setting up python with visual studio code. Having one issue. xringo 2 5,372 May-21-2018, 12:09 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020