Please I need help. I just started learning to code in python. i just got the hang of sending Market orders and trailing stop orders through code. A bracket order is perfectly what i need. but the Bracket order in the Documentation using Alpaca_Py is not correct. the imports are incorrect and I’m not really sure what my next steps are so anyone who can point me in the right direction with some explanation of the though process behind it cause I’m still very new to pyhton.
@AASAAQWE The alpaca-py
SDK can be a bit daunting at first with all the imports it requires, but I can perhaps help. Specifically, you asked
why bracket orders need to be separated into the different functions and why can’t they just be put into one function like a market order?
All it takes to submit a bracket order is a single statement. One doesn’t need to wrap it in a function unless it makes sense in your logic to do it that way. The entry (or parent) order can either be a regular market order or a limit order. To turn it into a bracket order (which is really a group of three separate orders) simply add the following to the order request
order_class = OrderClass.BRACKET,
stop_loss=StopLossRequest(stop_price=300.00),
take_profit=TakeProfitRequest(limit_price=400.00)
That specifies 1) that you want a BRACKET order and 2) the associated stop loss order and 3) the associated take profit limit order. You don’t need to specify the time in force, or the side, the symbol, or the qty for the ‘leg’ orders. Those values are copied from the original parent order.
So the coplete code to submit a bracket order (buying 1 share of SPY) would look like this
# install the alpaca-py SDK if needed
!pip install -q alpaca-py
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest, LimitOrderRequest, StopLossRequest, TakeProfitRequest
from alpaca.trading.enums import OrderSide, OrderClass, TimeInForce
ALPACA_API_KEY = 'xxxxx'
ALPACA_API_SECRET_KEY = 'xxxxx'
client = TradingClient(api_key=ALPACA_API_KEY, secret_key=ALPACA_API_SECRET_KEY)
# Bracket order with market order as initial 'parent' order
market_bracket_order = client.submit_order(MarketOrderRequest(
symbol='SPY',
qty=1,
side=OrderSide.BUY,
limit_price=350.00,
time_in_force=TimeInForce.DAY,
order_class = OrderClass.BRACKET,
stop_loss=StopLossRequest(stop_price=300.00),
take_profit=TakeProfitRequest(limit_price=500.00)
))
# Bracket order with limit order as initial order
limit_bracket_order = client.submit_order(LimitOrderRequest(
symbol='SPY',
qty=1,
side=OrderSide.BUY,
limit_price=350.00,
time_in_force=TimeInForce.DAY,
order_class = OrderClass.BRACKET,
stop_loss=StopLossRequest(stop_price=300.00),
take_profit=TakeProfitRequest(limit_price=500.00)
))
Of course a functioning algo would have more code than this, and it is good practice to put the submit_order
methods in a try-except
statement (in case it fails for some reason) but this is basically all that’s needed.