import sys
from ib_async import IB, Stock, MarketOrder

ib = IB()
try:
    ib.connect('127.0.0.1', 7497, clientId=11)

    contract = Stock("MU", "SMART", "USD")
    ib.qualifyContracts(contract)

    order = MarketOrder("SELL", 1)
    trade = ib.placeOrder(contract, order)

    for _ in range(20):
        ib.sleep(0.5)
        status = trade.orderStatus.status
        if status not in ("PendingSubmit", "PreSubmitted", ""):
            break

    fill_price = trade.orderStatus.avgFillPrice or "pending"
    print(f"Order ID:    {trade.order.orderId}")
    print(f"Fill price:  {fill_price}")
    print(f"Status:      {trade.orderStatus.status}")

    if "cancel" in trade.orderStatus.status.lower():
        print("Rejected. Log:")
        for entry in trade.log:
            print(" ", entry)
        sys.exit(1)

except Exception as e:
    print(f"Error: {e}")
    sys.exit(1)
finally:
    ib.disconnect()
