Accessing Tradier Brokerage API Using JavaScript

The Tradier Brokerage API provides developers with easy access to market data and trading functionality. In this tutorial, we will demonstrate how to access the Tradier Brokerage API using JavaScript.

Getting Started with Tradier Brokerage API

Before we get started, you will need to sign up for a Tradier Brokerage API account. Once you have signed up, you can retrieve your Access Token from the Tradier Developer Portal.

Making a Request to the API

To make a request to the Tradier Brokerage API, we will be using the fetch function in JavaScript. Here is a sample code snippet that you can use:

fetch(`https://api.tradier.com/v1/markets/quotes?symbols=AAPL`, {
  headers: {
    'Authorization': 'Bearer ' +accessToken,
    'Accept': 'application/json'
  }
})
.then(response => response.json())
.then(data => console.log(data));

The above code snippet will retrieve the current market quote for the AAPL (Apple Inc.) stock.

Retrieving Stock History

To retrieve the historical data for a stock, you can use the /v1/markets/history endpoint. Here is an example code snippet that shows how to retrieve stock history in JavaScript:

fetch(`https://api.tradier.com/v1/markets/history?symbol=AAPL&interval=monthly`, {
  headers: {
    'Authorization': 'Bearer ' +accessToken,
    'Accept': 'application/json'
  }
})
.then(response => response.json())
.then(data => console.log(data));

In the above code, we are retrieving the monthly historical data for the AAPL stock.

Placing an Order

You can place an order using the /accounts/<account_id>/orders endpoint. Here is an example code snippet that shows how to place an order:

fetch(`https://api.tradier.com/v1/accounts/<account_id>/orders`, {
  headers: {
    'Authorization': 'Bearer ' +accessToken,
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  method: 'POST',
  body: JSON.stringify({
    'class': 'equity',
    'symbol': 'AAPL',
    'side': 'buy',
    'quantity': 1,
    'type': 'market',
    'duration': 'gtc'
  })
})
.then(response => response.json())
.then(data => console.log(data));

In the above code snippet, we are placing a buy market order for one share of AAPL stock.

Conclusion

In this tutorial, we have demonstrated how to access the Tradier Brokerage API using JavaScript. With these code snippets, you can quickly retrieve market data, stock history, and place an order using the API.

Related APIs