How To Consume Alpaca Trade API Using Flask

This rest api tutorial help to access realtime free Trading API using Python.We will create simple python flask application and access Alpaca API.We will access account information alpaca using Rest API.

I am using alpaca-trade-api-python python libs to access Alpaca API.This a python library for the Alpaca Commission Free Trading API.It allows rapid trading algo development easily, with support for the both REST and streaming data interfaces.

The only dependency of this libs is supports only python version 3.6 and above, due to the async/await and websockets module dependency.

How To Consume Alpaca Trade API

We will use flask micro-api framework and python 3.6+.Created a new folder /alpaca-api-example into python workspace and cd into this folder.

$cd alpaca-api-example

Let’s install all dependencies of this example by running following command.
alpaca-api-example$ py -m pip install flask flask_cors flask_restful alpaca-trade-api-python

We will create api.py file and added below code into this file –

from flask import Flask
from flask_restful import Resource, Api
from flask_cors import CORS
import json
import alpaca_trade_api as tradeapi

app = Flask(__name__)
CORS(app) ## To allow direct AJAX calls

@app.route('/account', methods=['GET'])
def get_account():
    try:
        api = tradeapi.REST('<key_id>', '<secret_key>', api_version='v2')

# Get our account information.
res = api.get_account()

# Check if our account is restricted from trading.
if res.trading_blocked:
print('Account is currently restricted from trading.')
        return r.json()

   except Exception as e:
        print('unable to services from salesforce.')
        print(e.strerror)

if __name__ == '__main__':
   app.run(debug = True)

The defaults API version is ‘v2’. However, if you want to use ‘v1’ version, You may need to specify api_version='v1' to properly use the API until you migrate.

The Alpaca API requires API key ID and secret key, which you can obtain from the web console after you sign in.

You can pass key_id and secret_key to the initializers of REST or StreamConn as arguments​.