...

Algotrading For Dummies

A super-simple guide to full-stack algotrading using modern financial services and Python.

Our Chosen Technologies


These three services are all you need for algotrading, even excluding the need for a database.

...
Tradier

The easiest to use Algotrading brokerage on the market. Brokerage includes simple rest to api to open orders using the 'side' system to close any open position (buy or short).

Find out more

...
Polygon.io

The leading financial market data platform with 100% coverage over the stocks, options, crypto and forex markets. All data is stored in the cloud eliminating the need for any database.

Find out more

...
AWS Lambdas

The leader in executing serveless cloud functions with a very generous free-tier. Combined with tradier and polygon.io, and cron schedules, you have a full-stack algotrading platform.

Find out more

Tradier For Trading


In this section, I'll show you how easy it is to trade using the Tradier REST API and Python. After writing the place_order() and get_positions() functions, you'll be able to open and view trades in single lines of code! Besides that, various pros of using Tradier as your brokerage are listed below.


Commission-free
All Contracts and Equities sales have no fees. Unheard of for robust algotrading platforms.
Extended-hours Trading
Tradier has extended-hours from 4-8 pm, this can be a life saver to react to negative (or positive) press.
Simple Rest API
Orders are executed through a rest-api, enabling development on any language or front-end framework.
Easy Ordering system
All orders are abstracted as ordering from a side. For example, "buy" vs"sell" and "sell_short" vs "buy_to_cover".
Database-free
All orders, purchases, and positions are stored in the cloud, eliminating the need for a database.

0. Brokerage Account Preparation

Create an account:
https://onboarding.tradier.com/signup
Login to the dashboard:
https://dash.tradier.com
Get your credentials:
https://dash.tradier.com/settings/api

1. Placing an order in one function

▪ The only Python package you need is the "requests" package.
▪ To simplify the code, we're only going to execute market orders at the current price.

import requests

ACCOUNT_ID   = "**************"
ACCESS_TOKEN = "**************"


def place_order(symbol, side, quantity):

  response = requests.post(f'https://api.tradier.com/v1/accounts/{ACCOUNT_ID}/orders',
      data={
        'class': 'equity', 'type': 'market', 'duration': 'day', 
        'symbol': symbol, 'side': side, 'quantity': quantity, 
      },
      headers={ 'Authorization': 'Bearer {}',format(ACCESS_TOKEN), 'Accept': 'application/json' }
  )

  return response.json()
            

2. Viewing all open positions

▪ Function returns all positions on the Tradier Dashboard as json.

import requests

ACCOUNT_ID   = "**************"
ACCESS_TOKEN = "**************"


def get_positions():

  response = requests.post(f'https://api.tradier.com/v1/accounts/{ACCOUNT_ID}/orders',
      headers= { 'Authorization': 'Bearer {}',format(ACCESS_TOKEN), 'Accept': 'application/json' }
  )

  return response.json()['positions']['position']
            

3. Examples

▪ Wrapping code in functions enables ordering and viewing positions in single lines of code.
            
''' add functions from above '''  

order     : dict = place_order('AAPL', 'buy', '10') 
positions : list = get_positions()

print(order, positions)
            
            

'''''''''''''''''''''''''''''' 
  A dict of order metadata 
''''''''''''''''''''''''''''''           
{
  "order": {
    "id": 257459,
    "status": "ok",
    "partner_id": "c4998eb7-06e8-4820-a7ab-55d9760065fb"
  }
}

'''''''''''''''''''''''''''''' 
  A list of all open positions 
'''''''''''''''''''''''''''''' 
[
  {
    "cost_basis": 1478.1,
    "date_acquired": "2018-08-08T14:41:11.405Z",
    "id": 130089,
    "quantity": 10.00000000,
    "symbol": "AAPL"
  },
]

              
              

Polygon.io For Data


Well you can't open any trades if you don't have a strategy. This section details usage of the Polygon.io API in Python, specifically getting the RSI (Relative Strength Index) of stocks and fetching all tradeable symbols in the stock market (NASDAQ/NYSE). Some of my favorite advantages of using Polygon.io are listed below.


Real-Time and Historical Data
100% coverage of quotes, aggregates, and reference data for stocks, options, crypto, and forex.
Market Snapshot API
No other financial data provider has an API to query all live equity quotes in one call.
Unlimited Rate Limit (Starter+)
Combined with the snapshot API, entire equity markets can be updated every second.
Wide Language Support
Along with the REST and Websocket APIs, the Polygon team has clients across multiple languages.
Delisted Equity Support
Unlike other providers, if an equity (such as a stock) is delisted, Polygon.io doesn't discard the data.

0. Account Preparation

Create an account:
https://polygon.io/?auth=signup
Login Here:
https://polygon.io/?auth=login
Get your api-key:
https://polygon.io/dashboard/api-keys

1. Getting the RSI of a stock in one function

▪ The only variable you need to use Polygon.io is your API_KEY

import requests

API_KEY   = "**************"

def get_rsi(symbol):
  response = requests.post(f'https://api.polygon.io/v1/indicators/rsi/{symbol}',
      data={ "timespan":"day", "window":"14", "apiKey"=API_KEY }
  )

  return response.json()['results']['values']
            

2. Getting all active stocks in the stock market

▪ The tickers endpoint is very important as there aren't many providers who give the list of all equities programatically in the stock market.
              
import requests

API_KEY   = "**************"

def get_symbols():
  response = requests.post(f'https://api.polygon.io/v3/reference/tickers?active=true',
      data={ "active":True, "apiKey"=API_KEY }
  )

  return response.json()['results']
            

3. Examples

▪ Using functions make these api features executable in single statements.
▪ Example responses are below highlighted in green.
            
''' add functions from above '''

rsi       : list = get_rsi('AAPL', 'buy', '10') 
positions : list = get_symbols()

print(order, positions)
            
            
       
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
A list of RSI Values (Daily)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
[
  {
    "timestamp": 1517562000016,
    "value": 75.139
  },
  . 
  . 
  . 
]

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
A list of records of every active stock in the stock market
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
[
  {
      "active": true,
      "cik": "0001090872",
      "composite_figi": "BBG000BWQYZ5",
      "currency_name": "usd",
      "last_updated_utc": "2021-04-25T00:00:00Z",
      "locale": "us",
      "market": "stocks",
      "name": "Agilent Technologies Inc.",
      "primary_exchange": "XNYS",
      "share_class_figi": "BBG001SCTQY4",
      "ticker": "A",
      "type": "CS"
  }
  .
  . 
  .
]
              

AWS Lambdas For Execution


So you have code to open/close trades, find stocks that are overbought and oversold, and you can now query every stock in the NASDAQ and NYSE. You can trade now... with lambdas... In this section, we'll wrap everything up by making shceduled lambdas that can open new-trades and close current-positions on Tradier based on the RSI indicator from Polygon.io. As always, my favorite features will be listed below.


Serverless Cloud Functions
Enables developers to write small chunks of code to be bursted out based on specific events.
Scheduling with cron
Individual or groups of Lambdas functions can be executed in repeated cycles of hours, days or months
Nested Lambdas
Single Lambdas can fire other lambdas and even switch ec2 machines on/off.
Generous free-tier
1 Million free requests/month with 3.2 Million CPU Seconds

0. AWS Account Preparation

Create an account here:
https://portal.aws.amazon.com/billing/signup#/start/email
"Hello World" guide here:
https://aws.amazon.com/getting-started/hands-on/run-serverless-code/
Cron scheduling guide here:
https://docs.aws.amazon.com/lambda/latest/dg/services-cloudwatchevents-expressions.html

1. A lambda to buy a share of AAPL when it's RSI is <= 30


''' import code from above '''

TICKER   : str   = "AAPL"
AAPL_RSI : float = get_rsi(TICKER)

if AAPL_RSI <= 30:
  place_order(TICKER, 'buy', '10')

            

2. A lambda to buy any stock with an RSI <= 30

| 0 * * * 1-5 | A cron example for running code every hour Mon-Fri
              
''' import code from above '''

ALL_TICKER_INFO   : str  = get_symbols()
SYMBOLS           : list = [ record["ticker"] for ticker in ALL_TICKER_INFO ]

for ticker in SYMBOLS:
  if get_rsi(ticker) <= 30:
    place_order(ticker, 'buy', '1')
            

3. A Lambda to close any position if its RSI >= 70

Assertion: This code checks if any of your positions are oversold. It should be executed every minute of an active trading day to prevent slippage and generate maximum profit.
| * 9-16 * * 1-5 | A cron example for running code every minute from 9am-4pm Mon-Fri
            
''' import code from above '''

ALL_POSITIONS : list = get_positions()
for position in ALL_POSITIONS:

  side     : str = "sell"
  ticker   : str = position["symbol"]
  quantity : int = position["quantity"]

  if get_rsi(ticker) >= 70:
    place_order(ticker, side, quantity)
            
            

Now You're An Algotrading Super Hero


With this guide, you now have the ability to develop and excecute your own trading/investing models. With these three technologies, you'll be able to write any stock strategy and safely execute open and close orders on your Lambdas. It's never been a better time than this to learn algotrading. Below I'll list some more things you can do or research on your own.


Trading Off Quarterly Reports
You can get the financial numbers from 10-Q forms using the "Ticker Events" and "Stock Financials VX" APIs.
Stocks/Crypto Relations
Using the "Snapshots" APIs of the Stocks and crypto products, develop relation models across multiple markets.
Using Breaking News
Using the "News API", you can trade any stock if a breaking headline is released near market open.
Adding More Technical Analysis
You can add more indicators such as the SMA and EMA to create higher complexity models.

About Me


I'm a Senior from the University at Buffalo with a passion for big-data and algorithmic trading. In the past I've worked on many projects collecting and storing road/financial data and know the importance of choosing the right technologies for every task. Below I've included a 3-part tutorial on the basics of executing automatic trades.

© University at Buffalo : Lloyd Tanedo