Simple code to place a stock order with Alpaca and Python.

Simple code to place a stock order with Alpaca and Python.

I’m loving Alpaca more and more for back-testing and automated trading. One of the first items on my to-do list was to create very simply code for placing a buy or sell order. This example is the most basic of orders with the defaults set to a buy limit order.

You can sell a stock by changing the order_side variable from ‘buy’ to ‘sell’ to sell. You can use a market order by changing the order_type from ‘limit’ to ‘market’.

To run this you will need an alpaca API key. You can get this for free from Alpaca.Markets. Also note, Alpca is commission free and requires a margin account with minimum of $2000 to start.

import alpaca_trade_api as tradeapi
import pandas as pd

KEY = '#'

SECRET_KEY = '#'


symbol = 'CHK'

order_side = 'buy'  #can use 'sell' here to sell the position.

order_type = 'limit'  #can be market as well.

total_shares = 100

limit_price = 1.28


#Base url only changes when we go from paper trading to live trading!
BASE_URL = 'https://paper-api.alpaca.markets'

api = tradeapi.REST(KEY, SECRET_KEY, base_url=BASE_URL, api_version='v2') 

account = api.get_account()

api.list_positions()


existing_orders = api.list_orders(limit=500)

for order in existing_orders:
    if order.symbol == symbol:
        print("There is already an order for %s.  %s" % (symbol,str(order)))
        exit()

try:
    o = api.submit_order(
        symbol=symbol, qty=str(total_shares), side=order_side,
        type=order_type, time_in_force='day',
        limit_price=str(limit_price)
        )

    print(o)
except Exception as e:
    print(e)


Leave a Reply