# Bracket Order Code Example with alpaca-py Library

**URL:** <https://forum.alpaca.markets/t/bracket-order-code-example-with-alpaca-py-library/12110>\
**Category:** Alpaca Trading\
**Created:** [April 4, 2023, 10:34pm UTC](https://forum.alpaca.markets/t/bracket-order-code-example-with-alpaca-py-library/12110 "2023-04-04T22:34:37Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![phellstrand](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.alpaca.markets/phellstrand/32/4169_2.png) [@phellstrand](https://forum.alpaca.markets/u/phellstrand)\
**Post date:** [April 4, 2023, 10:34pm UTC](https://forum.alpaca.markets/t/bracket-order-code-example-with-alpaca-py-library/12110/1 "2023-04-04T22:34:37Z")

</div>

I struggled to find adequate documentation on bracket orders with the new and updated alpaca-py library, so I figured I’d post the below example for someone struggling to find an example in the future.

## Imports

```auto
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest, TakeProfitRequest, StopLossRequest
from alpaca.trading.enums import OrderSide, TimeInForce, QueryOrderStatus, OrderClass

```

## Keys

```auto
API_KEY = "<YOUR KEY>"
SECRET_KEY = "<YOUR SECRET>"

```

## Variables

```auto
trading_client = TradingClient(API_KEY, SECRET_KEY, paper=True)

```

## Functions

`def main():`

### Request a Bracket market order (calling Bracket market order function)

```auto
market_order_data = bracket_order(
        "AAPL", 1, 100, 200, OrderSide.BUY, TimeInForce.GTC
    )

```

### Submit market order

`submit_order(market_order_data)`

### Bracket market order function

```auto
def bracket_order(ticker, size, stop, take_profit, order_side, tif):
    stop_loss_request = StopLossRequest(
    stop_price=stop
    )
    take_profit_request = TakeProfitRequest(
    limit_price=take_profit
    )
    market_order_data = MarketOrderRequest(
        symbol=ticker,
        qty=size,
        side=order_side,
        time_in_force=tif,
        order_class = OrderClass.BRACKET,
        stop_loss=stop_loss_request,
        take_profit=take_profit_request
    )
    return market_order_data

```

### Submit an order and print the returned object function

```auto
def submit_order(order_data):
    order = trading_client.submit_order(order_data)
    for property_name, value in order:
        print(f'"{property_name}": {value}')

```

## Calling main() when running script directly

```auto
if __name__ == " __main__":
    main()

```

Happy trading!  
P

---

<div class="post-metadata">

**Author:** ![Carlos\_Santana](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.alpaca.markets/carlos_santana/32/5269_2.png) [@Carlos\_Santana](https://forum.alpaca.markets/u/Carlos_Santana)\
**Post date:** [April 5, 2023, 11:42am UTC](https://forum.alpaca.markets/t/bracket-order-code-example-with-alpaca-py-library/12110/2 "2023-04-05T11:42:50Z")

</div>

Thank you! Do you think it is possible to have a limit order and when this is filled a market on close order is submitted to exit on the close?

---

<div class="post-metadata">

**Author:** ![phellstrand](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.alpaca.markets/phellstrand/32/4169_2.png) [@phellstrand](https://forum.alpaca.markets/u/phellstrand)\
**Post date:** [April 11, 2023, 1:59am UTC](https://forum.alpaca.markets/t/bracket-order-code-example-with-alpaca-py-library/12110/3 "2023-04-11T01:59:28Z")

</div>

Yes, and if you simply wanted to close everything before close end of week, you could do something like this. To close it each day just remove `and next_open() >= 63:`

```auto
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import (
    MarketOrderRequest,
    StopOrderRequest,
    LimitOrderRequest,
    StopLimitOrderRequest,
    TrailingStopOrderRequest,
    GetOrdersRequest,
    GetOrderByIdRequest,
    ReplaceOrderRequest,
    TakeProfitRequest,
    StopLossRequest,
    ClosePositionRequest,
    GetAssetsRequest,
    GetPortfolioHistoryRequest,
    CancelOrderResponse,
    GetCalendarRequest
)
from alpaca.trading.enums import (
    OrderSide,
    TimeInForce,
    AssetClass,
    QueryOrderStatus,
    OrderClass,
)
from alpaca.data.historical import StockHistoricalDataClient

```

```auto
from datetime import datetime
import time
from pytz import timezone
import sys
import os
tz = timezone("EST")

```

def main():

```auto
def main():

while not trading_client.get_clock().is_open: # Set to not
        print(f"{datetime.now(tz)} - Market Closed, keep checking")
        time.sleep(60) #60
        continue
    else:
        print(f"{datetime.now(tz)} - Closing any unwanted open orders and positions")
        print(trading_client.close_all_positions(cancel_orders=True))
        time.sleep(5)
        print(f"{datetime.now(tz)} - Executing trades")
        market_order_data = bracket_order("AAPL", 1, 100, 200, OrderSide.BUY, TimeInForce.GTC)
        print(submit_order(market_order_data))
        while trading_client.get_clock().is_open and market_closing() > 12 and next_open() >= 63:
            print(f"{datetime.now(tz)} - Market not closing soon and week not ending")
            time.sleep(60) #60
            continue
        else:
            print(f"{datetime.now(tz)} - Closing all open orders and trades to end the week")
            trading_client.close_all_positions(cancel_orders=True)
            while trading_client.get_clock().is_open:
                print(f"{datetime.now(tz)} - Waiting for market to close for the week to exit program")
                time.sleep(60) #60
                continue
            else:
                sys.exit(f"{datetime.now(tz)} - Exiting to restart program")

```

```auto
# Market order function
def market_order(ticker, size, order_side, tif):
    market_order_data = MarketOrderRequest(
        symbol=ticker,
        qty=size,
        side=order_side,
        time_in_force=tif,
    )
    return market_order_data

```

```auto
# Stop order function
def stop_order(ticker, size, order_side, tif, stop):
    stop_order_data = StopOrderRequest(
        symbol=ticker, qty=size, side=order_side, time_in_force=tif, stop_price=stop
    )
    return stop_order_data

```

```auto
# Submit an order and print the returned object function
def submit_order(order_data):
    order = trading_client.submit_order(order_data)
    for property_name, value in order:
        print(f'"{property_name}": {value}')

```

```auto
# Cancel_all open orders and print each of them function
def cancel_all():
    positions = trading_client.cancel_orders()
    for position in positions:
        for property_name, value in position:
            print(f'"{property_name}": {value}')

```

```auto
def market_closing():
    est = datetime.now(tz).timestamp()
    market_close = trading_client.get_clock().next_close.timestamp()
    time_to_close = int((market_close - est) / 60) # Minutes to next close
    return time_to_close
    

def next_open():
    market_close = trading_client.get_clock().next_close.timestamp()
    market_open = trading_client.get_clock().next_open.timestamp()
    time_to_next_open = int((market_open - market_close) / 3600) # Hours to next open
    return time_to_next_open

```

```auto
if __name__ == " __main__":
    main()

```

---

<div class="post-metadata">

**Author:** ![Carlos\_Santana](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.alpaca.markets/carlos_santana/32/5269_2.png) [@Carlos\_Santana](https://forum.alpaca.markets/u/Carlos_Santana)\
**Post date:** [April 11, 2023, 4:20am UTC](https://forum.alpaca.markets/t/bracket-order-code-example-with-alpaca-py-library/12110/4 "2023-04-11T04:20:44Z")

</div>

Wow thank you! I am hoping they could include some trigger mechanism in the future like IBKR has it in their order logic.

---

<div class="post-metadata">

**Author:** ![Carlos\_Santana](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.alpaca.markets/carlos_santana/32/5269_2.png) [@Carlos\_Santana](https://forum.alpaca.markets/u/Carlos_Santana)\
**Post date:** [April 17, 2023, 4:05am UTC](https://forum.alpaca.markets/t/bracket-order-code-example-with-alpaca-py-library/12110/5 "2023-04-17T04:05:47Z")

</div>

The documentation is faulty and not updated. Wondering if I should put more money into Alpaca.

---

<div class="post-metadata">

**Author:** ![phellstrand](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.alpaca.markets/phellstrand/32/4169_2.png) [@phellstrand](https://forum.alpaca.markets/u/phellstrand)\
**Post date:** [April 18, 2023, 1:16am UTC](https://forum.alpaca.markets/t/bracket-order-code-example-with-alpaca-py-library/12110/6 "2023-04-18T01:16:45Z")

</div>

Yes, the docs on the website are outdated, and they do have updated docs, it’s just not full of context or examples. I’ve been successful using this: [Alpaca-py](https://alpaca.markets/docs/python-sdk/index.html)

---

<div class="post-metadata">

**Author:** ![AASAAQWE](https://avatars.discourse-cdn.com/v4/letter/a/b782af/32.png) [@AASAAQWE](https://forum.alpaca.markets/u/AASAAQWE)\
**Post date:** [October 26, 2023, 5:59am UTC](https://forum.alpaca.markets/t/bracket-order-code-example-with-alpaca-py-library/12110/7 "2023-10-26T05:59:12Z")

</div>

I plugged this into PyCharm, and it still says its incomplete. please if you can explain why bracket orders need to be separates into the different function and why can’t they just be put into one function like a market order. for original post. I’m really trying and struggling to understand bracket orders, so any help is very appreciated.

---

<div class="post-metadata">

**Author:** ![Dan\_Whitnable\_Alpaca](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.alpaca.markets/dan_whitnable_alpaca/32/1658_2.png) [@Dan\_Whitnable\_Alpaca](https://forum.alpaca.markets/u/Dan_Whitnable_Alpaca)\
**Post date:** [October 27, 2023, 6:50pm UTC](https://forum.alpaca.markets/t/bracket-order-code-example-with-alpaca-py-library/12110/8 "2023-10-27T18:50:27Z")

</div>

@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

```auto
# 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)
 

```

```auto
# 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)
          ))

```

```auto
# 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.

---

<div class="post-metadata">

**Author:** ![Mike1](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.alpaca.markets/mike1/32/6550_2.png) [@Mike1](https://forum.alpaca.markets/u/Mike1)\
**Post date:** [September 26, 2024, 7:24pm UTC](https://forum.alpaca.markets/t/bracket-order-code-example-with-alpaca-py-library/12110/9 "2024-09-26T19:24:17Z")

</div>

Excellent answer Dan! What to do with limit\_bracket\_order but with a trailing stop loss and/or take-profit? Is stop\_loss and take\_profit parameter compatible with any request type, eg trailing requests as well?  
Thank you @Dan_Whitnable_Alpaca
