Program trading orders with Alpaca API in Python

Learn how to automate trading strategies by programming buy and sell orders with Python using the Alpaca API.

In trading platforms, you can request buy or sell orders on a financial asset.

Trading platform screen showing a buy order for Bitcoin with details such as the symbol BTCUSD and the amount invested.
F1. Buy order for Bitcoin

You can program a bot to execute your orders to automate your operations.

In this tutorial, you’ll learn to request orders programmatically with the Alpaca API using a demo account.

Disclaimer: This tutorial is for educational purposes to teach you to program with practical cases. It is not an investment recommendation.

Questions

  1. How do you authorize the code to execute trading operations with your Alpaca account?
  2. What general information do you have about your demo account?
  3. How do you create a buy order for a financial asset?
  4. What does the GTC parameter mean in a buy order? Why is it important?
  5. How do you close an open position on a specific asset?
  6. How do you view updated information on your portfolio after performing operations?

Methodology

Create an Account on Alpaca

Register at Alpaca and generate an API Key to validate your programmatic access.

To avoid risks, do not register any payment method when creating your account.

API_KEY = 'YOUR_API_KEY'
API_SECRET = 'YOUR_API_SECRET'

Account Properties

Once you have installed the Alpaca library:

pip install alpaca-py

You create the trading client instance in demo mode, paper=True, to validate your connection to the API.

from alpaca.trading.client import TradingClient
client = TradingClient(API_KEY, API_SECRET, paper=True)

Request your account information to verify that everything is in order.

data = client.get_account()

You start with a balance of $100,000 in your demo account.

View of the initial balance of a demo account in Alpaca, showing a balance of 100,000 dollars.
F2. Initial balance in Alpaca demo account

Request First Order

Let’s go all-in on Bitcoin BTCUSD with the available balance.

To register the order, create a MarketOrderRequest object specifying the conditions.

  • notional is the amount of money you want to invest in the order. If you want to buy a specific number of shares, you should use the qty parameter.
  • GTC Good Till Cancelled indicates that the order will remain active until executed.
order = requests.MarketOrderRequest(
    symbol='BTCUSD',
    notional=100_000,
    side=enums.OrderSide.BUY,
    time_in_force=enums.TimeInForce.GTC,
)

client.submit_order(order)

If you visit your active orders, you’ll see the buy order for Bitcoin.

Would this be interesting to one of your friends? Share it with them.

In our case, the order was executed by buying 1.40 Bitcoins at an average price of $69,837.9552.

Trading platform screen showing a buy order for Bitcoin with details such as the symbol BTCUSD and the amount invested.
F1. Buy order for Bitcoin

The execution of the order in Bitcoin should be immediate. However, for other financial assets, the order may take time to execute.

Close Asset Position

Now, you have an asset as an open position in your account.

To close the position, you’ll need the asset_id of the asset.

position = client.get_open_position('BTCUSD')
client.close_position(symbol_or_asset_id=position.asset_id)
Screenshot showing the process of closing an open position in Bitcoin, with details of the operation.
F4. Process of closing position in Bitcoin

Portfolio Balance

Finally, you’ll observe your portfolio with the updated balance on the Alpaca platform.

We noticed that the balance increased by $92.86 after the operations.

Summary of the portfolio balance on the Alpaca platform after performing operations, showing an increase in the balance.
F5. Updated portfolio balance on Alpaca

And that’s how you can use programming to make decisions that are reflected in reality using APIs.

Questions? Let’s talk below in the comments.

Conclusions

  1. Authorization for Trading Operations: TradingClient in demo mode paper=True for operating with the trading API.
  2. Demo Account Information: client.get_account retrieves information from the demo account, including balance and status.
  3. Creation of a Buy Order: client.submit_order creates and sends a MarketOrderRequest buy order for an asset specifying details such as amount and price.
  4. Use of GTC in Orders: enums.TimeInForce.GTC establishes that the order remains active until executed.
  5. Closing an Open Position: client.close_position closes an open position for a specific asset.
  6. Updated Visualization of Operations: all information about the operations performed is reflected on the Alpaca platform.

If you could program whatever you wanted, what would it be? The upcoming tutorial might cover it ;)

Let’s talk in the comments below.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to datons.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.