does orders within an IF sttament not work with IB API?

23 Views Asked by At

`Trying to set buy and sell orders by comparing the open price to the current price, the code works fine when not in an if statement. But when i put the buy/sell critieria into an if statement to do one or the other it does not recoginze the variables buy_trade and sell_trade

from ib_insync import *

ib = IB()
ib.connect('127.0.0.1', 7497, clientId=999)

contract = Stock('TSLA', 'SMART', 'USD')
order_placed_buy = False
order_placed_sell = False

def check_and_place_order():
global order_placed_buy, order_placed_sell
if not order_placed_buy and not order_placed_sell:
    # Fetch real-time market data for TSLA
    ticker = ib.reqMktData(contract, genericTickList='233', snapshot=False)
    ib.sleep(1)  # Wait for market data to arrive

    open_price = ticker.open
    current_price = ticker.marketPrice()
    quantity_sell = 10 / current_price
    quantity_buy = 20 / current_price

    if open_price * 0.98 >= current_price:  # Check if the price has dropped by 2%
        buy_order = MarketOrder('BUY', quantity_buy)  # Place a market buy order for $5
        buy_trade = ib.placeOrder(contract, buy_order)
        print("Market buy order placed", buy_trade)
        order_placed_buy = True

    elif open_price * 1.02 <= current_price:  # Check if the price has gone up by 2%
        sell_order = MarketOrder('SELL', quantity_sell)  # Place a market sell order for      $10/current share price
        sell_trade = ib.placeOrder(contract, sell_order)
        print("Market sell order placed", sell_trade)
        order_placed_sell = True

ib.pendingTickersEvent += check_and_place_order

# order = MarketOrder('BUY', 20)

# trade = ib.placeOrder(contract, order_placed_sell)

# print(trade)

# def orderFilled(trade, fill):
#     print("order has been filled")
#     print(trade)
#     print(fill)

# trade.fillEvent += orderFilled

ib.sleep(3)

# for trade in ib.trades():
#     print("== this is one of my trades =")
#     print(trade)

# for order in ib.orders():
#     print("== this is one of my orders ==")
#     print(order)

ib.run()`
0

There are 0 best solutions below