GithubHelp home page GithubHelp logo

alpaca-trade-api-js's Introduction

Alpaca Trade API JS

npm version CircleCI

Node.js library for Alpaca Trade API.

API Documentation

The REST API documentation can be found in https://docs.alpaca.markets. For detailed information about an endpoint, please consult the REST API docs. Documentation specific to this library can be found below.

Installation

npm install --save @alpacahq/alpaca-trade-api

Usage

Import the module first.

const Alpaca = require('@alpacahq/alpaca-trade-api')

Instantiate the API with config options (keyId, secretKey).

const alpaca = new Alpaca({
  keyId: 'AKFZXJH121U18SHHDRFO',
  secretKey: 'pnq4YHlpMF3LhfLyOvmdfLmlz6BnASrTPQIASeiU',
  paper: true,
})

Call methods, which will return a promise.

alpaca.getAccount().then((account) => {
  console.log('Current Account:', account)
})

The websocket api is a good way to watch and react to the market

const client = alpaca.websocket
client.onConnect(function() {
  console.log("Connected")
  client.subscribe(['trade_updates', 'account_updates', 'T.FB', 'Q.AAPL', 'A.FB', 'AM.AAPL'])
  setTimeout(() => {
    client.disconnect()
  }, 30 * 1000)
})
client.onDisconnect(() => {
  console.log("Disconnected")
})
client.onStateChange(newState => {
  console.log(`State changed to ${newState}`)
})
client.onOrderUpdate(data => {
  console.log(`Order updates: ${JSON.stringify(data)}`)
})
client.onAccountUpdate(data => {
  console.log(`Account updates: ${JSON.stringify(data)}`)
})
client.onStockTrades(function(subject, data) {
  console.log(`Stock trades: ${subject}, ${data}`)
})
client.onStockQuotes(function(subject, data) {
  console.log(`Stock quotes: ${subject}, ${data}`)
})
client.onStockAggSec(function(subject, data) {
  console.log(`Stock agg sec: ${subject}, ${data}`)
})
client.onStockAggMin(function(subject, data) {
  console.log(`Stock agg min: ${subject}, ${data}`)
})
client.connect()

Methods

As a general rule, required method parameters are passed as plain function arguments, and the final parameter is an object containing any optional parameters to the method.

Account API

Calls GET /account and returns the current account.

getAccount() => Promise<Account>

Orders API

Create Order

Calls POST /orders and creates a new order.

createOrder({
  symbol: string, // any valid ticker symbol
  qty: number,
  side: 'buy' | 'sell',
  type: 'market' | 'limit' | 'stop' | 'stop_limit',
  time_in_force: 'day' | 'gtc' | 'opg' | 'ioc',
  limit_price: number,
  stop_price: number,
  client_order_id: string // optional
}) => Promise<Order>

Get Orders

Calls GET /orders and returns a list of orders.

getOrders({
  status: 'open' | 'closed' | 'all',
  after: Date,
  until: Date,
  limit: number,
  direction: 'asc' | 'desc'
}) => Promise<Order[]>

Get Order by ID

Calls GET /orders/{id} and returns an order.

getOrder(uuid) => Promise<Order>

Get Order by Client ID

Calls GET /orders:by_client_order_id and returns an order by client_order_id. You can set client_order_id upon order creation to more easily keep track of your orders.

getOrderByClientOrderId(string) => Promise<Order>

Cancel Order

Calls DELETE /orders/{id} and deletes an order.

cancelOrder(uuid) => Promise

Positions API

Get Position

Calls GET /positions/{symbol} and returns a position.

getPosition(symbol) => Promise<Position>

Get All Positions

Calls GET /positions and returns all positions.

getPositions() => Promise<Position[]>

Assets API

Get All Assets

Calls GET /assets and returns assets matching your parameters.

getAssets({
  status: 'active' | 'inactive',
  asset_class: string,
}) => Promise<Asset[]>

Get information about an asset

Calls GET /assets/{symbol} and returns an asset entity.

getAsset(symbol) => Promise<Asset>

Calendar API

Calls GET /calendar and returns the market calendar.

getCalendar({ start: Date, end: Date }) => Promise<Calendar[]>

Data API

Get Bars

getBars(
  'minute' | '1Min' | '5Min' | '15Min' | 'day' | '1D',
  symbol | symbol[], // which ticker symbols to get bars for
  {
    limit: number,
    start: Date,
    end: Date,
    after: Date,
    until: Date
  }
)

Websockets

  • let websocket = alpaca.websocket: Create a websocket client instance.
  • websocket.connect(): Connect to the alpaca server using websocket.
  • websocket.subscribe(channels): Subscribe to the alpaca server and possibly Polygon server Possible channels: 'trade_updates', 'account_updates', 'T.', 'Q.', 'A.', AM.' This will unsubscribe from any previously subscribed channels. trade_updates and account_updates are for the alpaca server, the rest are for the Polygon server. For more information, please contact the relevant pages.
  • websocket.onOrderUpdate(function(data)): Register callback function for the channel 'trade_updates'.
  • websocket.onAccountUpdate(function(data)): Register callback function for the channel 'account_updates'.
  • websocket.onStockTrades(function(data)): Register callback function for the channel 'T.*'.
  • websocket.onStockQuotes(function(data)): Register callback function for the channel 'Q.*'.
  • websocket.onStockAggSec(function(data)): Register callback function for the channel 'A.*'.
  • websocket.onStockAggMin(function(data)): Register callback function for the channel 'AM.*'.

alpaca-trade-api-js's People

Contributors

motocombotag avatar smartchris84 avatar suddjian avatar umitanuki avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.