Closed windowshopr closed 10 months ago
To make this issue even easier, how could I use ib_insync
to place a trailing stop loss order as detailed on this page under the "Mosaic Example" section:
There you can define a trailing amount as a dollar value ($0.25 in that example), but I can only see a trailing percentage in the documentation for ib_insync? Maybe?
To update, this is the best I have so far:
# Route for accepting POST requests to open a new position
@app.route('/post-order', methods=['POST'])
def post_order():
# Get the option order details from the request. Assume the frontend is
# handling the validation of the data
data = request.json
ticker_symbol = str(data.get('ticker_symbol')).upper()
expiry = str(data.get('expiry'))
strike = float(data.get('strike'))
call_or_put = str(data.get('call_or_put')).upper()
order_size = int(data.get('order_size'))
limit_entry_price = float(data.get('limit_entry_price'))
stop_loss_price = float(data.get('stop_loss_price'))
take_profit_1_price = float(data.get('take_profit_1_price'))
# Create a contract for the option via ticker symbol
contract = Option(ticker_symbol, expiry, strike, call_or_put, 'SMART')
ib.qualifyContracts(contract)
# Create the initial bracket order, good for the day
parent_order = LimitOrder(action='BUY',
totalQuantity=order_size,
lmtPrice=limit_entry_price,
tif='DAY')
parent_order.transmit = False
# Create the take profit order
take_profit_1_order = LimitOrder(action='SELL',
totalQuantity=order_size,
lmtPrice=take_profit_1_price,
ocaGroup=ticker_symbol + "_OCA",
tif='GTC')
take_profit_1_order.transmit = False
# Create a custom trailing stop loss order that is part of the same
# OCA group as the take profit order
stop_loss_order = Order(action='SELL',
orderType="TRAIL",
totalQuantity=order_size,
auxPrice=round(limit_entry_price - stop_loss_price, 2),
ocaGroup=ticker_symbol + "_OCA",
tif='GTC')
)
stop_loss_order.transmit = True
# Place the bracket order
bracket_order = BracketOrder(parent=parent_order, takeProfit=take_profit_1_order, stopLoss=stop_loss_order)
trades = ib.placeOrder(contract, bracket_order)
# Wait until there's a log entry for the entry order
while not trades[0].log:
ib.sleep(1)
# Wait until the entry order is filled. This is not the appropriate way to do this,
# but for this example it's fine.
while True:
if trades[0].log[-1].status == 'Filled':
break
ib.sleep(1)
return jsonify({'message': 'Order placed successfully'})
...which I believe closely matches this setup:
The IB documentatation for orders can be found here:
Hey!
I've been working on this for a few hours, but am stuck on understanding if my syntax is correct, and given that the markets are usually closed when I get the chance to work on this, it's hard to test, so I'm hoping the gurus here can lend a hand.
I am creating a Flask endpoint that receives some Options order information to place a new options order. This endpoint spins up a new thread where it handles everything from order submission to actively monitoring the position.
Initially, I place a bracket order with a
LimitOrder
buy order, aLimitOrder
TP, and aStopOrder
for the SL. I make this a bracket order being mindful of thetransmit
property. You'll notice in the code that I have 2 TP levels, and I'll explain why in a bit, but for the initial order, I submit the higher TP level (TP2) along with the stop loss, the logic here being, if for some reason my connection to TWS Gateway is interrupted and my program can no longer actively manage the position, the "fail safes" are in place with the broker.With the order submitted, what I'm doing is watching the bid price of the contract. If the bid price >= TP1 level (not TP2, but TP1), I want to modify the SL from a
StopOrder
to aTrailingStopOrder
, such that once the price hits the first TP level, the SL is adjusted to break even/the entry limit price, and as the bid moves higher, so does the SL.I'm confused about the differences between
auxPrice
,trailStopPrice
,trailingPercent
, etc., and I'm not sure how to implement what I'm looking for. I've spent some time on this and have provided some nice comments to follow along with so I'm hoping someone here can help me set this up properly! Can be read pretty much from top to bottom to follow along with the logic as I've described it.Working with Python 3.8, Windows 10, IB Gateway, latest version of ib_insync, etc.
Thanks!!!