@alpacahq/alpaca-trade-api

Alpaca Trade API JS

npm version CircleCI
Node.js library for Alpaca Trade API .

API Documentation

The REST API software documentation can be found in hypertext transfer protocol : //docs.alpaca.markets. For detailed information about an end point, please consult the REST API department of commerce. Documentation particular to this library can be found below .

News

We introduced Typescript support recently, which allows you to use powerfully typed datum structures and better IDE have if you are using it.

Installation

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

Runtime Dependencies

  • Node.js v14.x or newer
  • npm version 6 and above

Usage

import the faculty first .

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

Instantiate the API with config options, obtained from the dashboard at app.alpaca.markets .

 const  alpaca  =  new  alpaca ( {
   keyId:  'AKFZXJH121U18SHHDRFO ' ,
   secretKey:  'pnq4YHlpMF3LhfLyOvmdfLmlz6BnASrTPQIASeiU ' ,
   wallpaper:  on-key ,
 } )

note : keyId and secretKey may besides be specified by setting the APCA_API_KEY_ID and APCA_API_SECRET_KEY environment variables, respectively. besides, rather than specifying paper, you may set APCA_API_BASE_URL as an environment variable to direct your API calls to the newspaper trade API .
Call methods, which will return a promise .

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

The websocket api is a good way to watch and react to the market we have 2 types of websockets :

  • data websocket: get updates to data equities
  • account/trade websocket: get updates on your account

please refer to this model code to see how to use the websockets .

Data WS

The Alapca websocket service now supports V2. Make certain you update your old sample code accordingly.
You could use it even if you do n’t have a fund account.

Methods

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

Account API

Get Account

Calls GET /account and returns the current report .

 getAccount ( )  = >  promise < account >

Account Configurations API

Get Account Configurations

Calls GET /account/configurations and returns the current account configurations .

 getAccountConfigurations ( )  = >  promise < AccountConfigurations >

Update Account Configurations

Calls PATCH /account/configurations to update the account configurations, and returns the update configurations .

 updateAccountConfigurations ( AccountConfigurations )  = >  promise < AccountConfigurations >

Get Account Activities

Calls GET /account/activities and returns account activities .

 getAccountActivities ( {
   activityTypes:  string  |  string [ ],  // Any valid activeness type
   until:  date ,
   after:  date ,
   focus:  drawstring ,
   date:  date ,
   pageSize:  numeral ,
   pageToken:  string
 } )  = >  promise < AccountActivity [ ] >

Portfolio History API

Get Portfolio History

Calls GET /account/portfolio/history and returns portfolio history .

 getPortfolioHistory ( {
   date_start:  date ,
   date_end:  date ,
   period:  '1M '  |  '3M '  |  '6M '  |  '1A '  |  'all '  |  'intraday ' ,
   timeframe:  '1Min '  |  '5Min '  |  '15Min '  |  '1H '  |  '1D ' ,
   extended_hours:  boolean
 } )  = >  promise < PortfolioHistory >

Orders API

Create Order

Calls POST /orders and creates a new regulate .

 createOrder ( {
   symbol:  string,  // any valid watch symbol
   qty:  total ,
   fanciful:  number,  // qty or fanciful required, not both
   side:  'buy '  |  'sell ' ,
   type:  'market '  |  'limit '  |  'stop '  |  'stop_limit '  |  'trailing_stop ' ,
   time_in_force:  'day '  |  'gtc '  |  'opg '  |  'ioc ' ,
   limit_price:  number,  // optional ,
   stop_price:  number,  // optional ,
   client_order_id:  string,  // optional ,
   extended_hours:  boolean,  // optional ,
   order_class:  string,  // optional ,
   take_profit:  object,  // optional ,
   stop_loss:  object,  // optional ,
   trail_price:  string,  // optional ,
   trail_percent:  string  // optional ,
 } )  = >  promise < club >

Get Orders

Calls GET /orders and returns a list of orders .

 getOrders ( {
   condition:  'open '  |  'closed '  |  'all ' ,
   after:  date ,
   until:  date ,
   limit:  total ,
   commission:  'asc '  |  'desc '
 } )  = >  promise < rate [ ] >

Get Order by ID

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

 getOrder ( uuid )  = >  promise < order >

Get Order by Client ID

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

 getOrderByClientOrderId ( bowed stringed instrument )  = >  promise < orderliness >

Update Order by ID

Calls PATCH /orders/{id} and updates an existing unfold order. The update regulate will have a new ID .

 replaceOrder ( uuid )  = >  promise < order >

Cancel Order

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

 cancelOrder ( uuid )  = >  promise

Cancel all Orders

Calls DELETE /orders and deletes all capable orders .

 cancelAllOrders ( )  = >  promise

Positions API

Get Position

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

 getPosition ( symbol )  = >  predict < situation >

Get All Positions

Calls GET /positions and returns all positions .

 getPositions ( )  = >  promise < status [ ] >

Close a Position

Calls DELETE /positions/{symbol} and liquidates your position in the given symbol .

 closePosition ( symbol )  = >  promise

Close all Positions

Calls DELETE /positions and liquidates all open positions .

 closeAllPositions ( )  = >  promise

Assets API

Get All Assets

Calls GET /assets and returns assets matching your parameters .

 getAssets ( {
   condition:  'active '  |  'inactive ' ,
   asset_class:  string
 } )  = >  promise < asset [ ] >

Get information about an asset

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

 getAsset ( symbol )  = >  predict < asset >

Calendar API

Calls GET /calendar and returns the grocery store calendar .

 getCalendar ( {  start:  date,  end:  date  } )  = >  promise < calendar [ ] >

Clock API

Calls GET /clock and returns the marketplace clock .

 getClock ( )  = >  promise < clock >

Watchlist API

available methods for you to use :

 module. exports  =  {
    getWatchlists ,
    getWatchlist ,
    addWatchlist ,
    addToWatchlist ,
    updateWatchlist ,
    deleteWatchlist ,
    deleteFromWatchlist ,
 }

Get All Watchlists

 alpaca. getWatchlists ( ). then ( ( response )  = >  {
   console. log ( reaction )
 } )

Get Specific Watchlist

  // xxxx.. are the watchlist id you get on creation or with get all
  alpaca. getWatchlist ( 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ' ). then ( ( response )  = >  {
    comfort. log ( reply )
  } )

Add a Watchlist

 alpaca. addWatchlist ( `` myWatchList '',  [ ] ). then ( ( reception )  = >  {
   cabinet. log ( response )
 } )

Add to Watchlist

 alpaca. addToWatchlist ( 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ',  `` AAPL '' ). then ( ( response )  = >  {
   console. log ( response )
 } )

Update a Watchlist

 alpaca. updateWatchlist ( `` myWatchList '',  [ `` AAPL '',  `` GOOG '' ] ). then ( ( response )  = >  {
   cabinet. logarithm ( reception )
 } )

Delete a Watchlist

 alpaca. deleteWatchlist ( 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ' ). then ( ( reaction )  = >  {
   console. log ( answer )
 } )

Delete from Watchlist

 alpaca. deleteFromWatchlist ( 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ',  `` AAPL '' ). then ( ( response )  = >  {
   console table. log ( answer )
 } )

Data API

Trades

 getTradesV2 (
   symbol:  string ,
   options:  GetTradesParams ,
   config?:  any ,
 ):  AsyncGenerator < AlpacaTrade,  

void

, unknown > ;
 getMultiTradesV2 (
   symbols:  array < string > ,
   options:  GetTradesParams ,
   config?:  any ,
 ):  predict < function < chain,  AlpacaTrade [ ] > > ;
 getMultiTradesAsyncV2 (
   symbols:  range < string > ,
   options:  GetTradesParams ,
   config?:  any ,
 ):  AsyncGenerator < AlpacaTrade,  

void

, nameless > ;
 getLatestTrade (
   symbol:  string ,
   config?:  any ,
 ):  promise < AlpacaTrade > ;
 getLatestTrades (
   symbols:  array < string > ,
   config?:  any ,
 ):  promise < map < string,  AlpacaTrade > > ;
Example
 const  trade  =  expect  alpaca. getLatestTrade ( 'AAPL ' ) ;
 comfort. log ( deal ) ;
{
   Timestamp:  '2022-04-14T13:54:24.907840256Z ',
   Exchange:  'P ',
   monetary value:  169.33,
   size:  100,
   Conditions: [  ' @ ' ],
   idaho:  12272,
   videotape:  'C '
}

Quotes

 getQuotesV2 (
   symbol:  string ,
   options:  GetQuotesParams ,
   config?:  any ,
 ):  AsyncGenerator < AlpacaQuote,  

void

, unknown > ;
 getMultiQuotesV2 (
   symbols:  array < string > ,
   options:  GetQuotesParams ,
   config?:  any ,
 ):  promise < map < chain,  any [ ] > > ;
 getMultiQuotesAsyncV2 (
   symbols:  array < string > ,
   options:  GetQuotesParams ,
   config?:  any ,
 ):  AsyncGenerator < AlpacaQuote,  

void

, unknown > ;
  getLatestQuote (
    symbol:  string ,
    config?:  any ,
 ):  promise < AlpacaQuote > ;
 getLatestQuotes (
    symbols:  array < chain > ,
    config?:  any ,
 ):  promise < map < string,  AlpacaQuote > > ;
Example
 const  trades  =  expect  alpaca. getMultiTradesV2 ( [ `` PFE '',  `` spy '' ],  {
   beginning:  `` 2022-04-18T08:30:00Z '' ,
   end:  `` 2022-04-18T08:31:00Z '' ,
   limit:  2 ,
 } ) ;
 console. log ( trades ) ;
 {
   'PFE '  = >  [
     {
       Timestamp:  '2022-04-18T08:30:59.988642304Z ', 

Read more: Forum Policy

Exchange: 'P ' , price: 53.25 , size: 5 , Conditions: [ array ] , id: 52983525028174 , videotape: 'A ' , symbol: 'PFE ' } ] , 'SPY ' = > [ { Timestamp: '2022-04-18T08:30:00.066013952Z ' , Exchange: 'P ' , price: 436.39 , size: 1 , Conditions: [ array ] , idaho: 52983525028949 , magnetic tape: 'B ' , symbol: 'SPY ' } ] }
Bars
  getBarsV2 (
    symbol:  string ,
    options:  GetBarsParams, 
    config?:  any ,
  ):  AsyncGenerator < AlpacaBar,  

void

, strange > ;
 getMultiBarsV2 (
   symbols:  range < string > ,
   options:  GetBarsParams ,
   config?:  any ,
 ):  promise < map < string,  any [ ] > > ;
  getMultiBarsAsyncV2 (
    symbols:  array < string > ,
    options:  GetBarsParams ,
    config?:  any ,
  ):  AsyncGenerator < AlpacaBar,  

void

, obscure > ;
  getLatestBar (
   symbol:  string ,
   config?:  any ,
 ):  promise < AlpacaBar > ;
 getLatestBars (
   symbols:  range < string > ,
   config?:  any ,
 ):  promise < map < string,  AlpacaBar > > ;
Example
 const  bars  =  alpaca. getBarsV2 ( `` AAPL '',  {
   start:  `` 2022-04-01 '' ,
   end:  `` 2022-04-02 '' ,
   timeframe:  alpaca. newTimeframe ( 30,  alpaca. timeframeUnit. min ) ,
   specify:  2 ,
 } ) ;
 const  got  =  [ ] ;
 for  expect  ( let  b  of  bars )  {
   got. push ( bel ) ;
 }
 comfort. log ( got ) ;
[
  {
     Timestamp:  '2022-04-01T08:00:00Z ',
     OpenPrice:  175.25,
     HighPrice:  175.88,
     LowPrice:  175.1,
     ClosePrice:  175.35,
     bulk:  30015,
     TradeCount:  721,
     VWAP:  175.357657
  },
  {
     Timestamp:  '2022-04-01T08:30:00Z ',
     OpenPrice:  175.32,
     HighPrice:  175.37,
     LowPrice:  175.26,
     ClosePrice:  175.26,
     volume:  5929,
     TradeCount:  123,
     VWAP:  175.332243
  }
]
Snapshots
 getSnapshot (
   symbol:  chain ,
   config?:  any ,
 ):  promise < AlpacaSnapshot > ;
 getSnapshots (
   symbols:  align < chain > ,
   config?:  any ,
 ):  promise < AlpacaSnapshot [ ] > ;
Example
 const  snapshot  =  expect  alpaca. getSnapshot ( `` TSLA '' ) ;
 console table. log ( snapshot ) ;
{
   symbol:  'TSLA ',
   LatestTrade: {
     Timestamp:  '2022-04-19T10:09:23.844940801Z ',
     Exchange:  'Q ',
     price:  1003,
     size:  501,
     Conditions: [  ' @ ',  'F ',  'T ' ],
     idaho:  1861,
     magnetic tape:  'C '
  },
   LatestQuote: {
     Timestamp:  '2022-04-19T10:10:09.139921353Z ',
     AskExchange:  'Q ',
     AskPrice:  1004.38,
     AskSize:  1,
     BidExchange:  'Q ',
     BidPrice:  1001,
     BidSize:  3,
     Conditions: [  'R ' ],
     tape:  'C '
  },
   MinuteBar: {
     Timestamp:  '2022-04-19T10:09:00Z ',
     OpenPrice:  1003,
     HighPrice:  1003,
     LowPrice:  1003,
     ClosePrice:  1003,
     volume:  647,
     TradeCount:  17,
     VWAP:  1003.071345
  },
   DailyBar: {
     Timestamp:  '2022-04-18T04:00:00Z ',
     OpenPrice:  989.19,
     HighPrice:  1014.92,
     LowPrice:  973.41,
     ClosePrice:  1004.29,
     volume:  17209682,
     TradeCount:  543314,
     VWAP:  997.42604
  },
   PrevDailyBar: {
     Timestamp:  '2022-04-14T04:00:00Z ',
     OpenPrice:  998.51,
     HighPrice:  1012.7099,
     LowPrice:  982.19,
     ClosePrice:  985,
     book:  19449944,
     TradeCount:  579328,
     VWAP:  991.712944
  }
}

More detail examples of standard data endpoints can be found in this file .

News
  getNews (
    options:  GetNewsParams ,
    config?:  any ,
  ):  promise < AlpacaNews [ ] > ;

Details of the options parameter can be found hera .

Example
  const  newsworthiness  =  expect  alpaca. getNews ( { } ) ;
  comfort. log ( news [ 0 ] ) ;
{
   id:  26682466,
   headline:  'Plug Power Enters Agreement With Walmart Pursuant To Which The Co. Will Deliver Liquid Green Hydrogen To New And Existing Walmart Sites In The United States ',
   generator:  'Bill Haddad ',
   CreatedAt:  '2022-04-19T10:09:38Z ',
   UpdatedAt:  '2022-04-19T10:09:39Z ',
   summary:  '',
   url:  'https : //www.benzinga.com/news/22/04/26682466/plug-power-enters-agreement-with-walmart-pursuant-to-which-the-co-will-deliver-liquid-green-hydrogen ',
   Images: [],
   Symbols: [  'PLUG ',  'WMT ' ],
   source:  'benzinga '
}

Data API – Crypto

All the functions are similar to the store ones .

Trades

  •    getCryptoTrades (
         symbol:  chain, 
         options:  GetCryptoTradesParams, 
         config?:  any ,
       ):  AsyncGenerator < CryptoTrade,  

    void

    , stranger > ;
  •    getLatestCryptoTrade (
         symbol:  string ,
         options:  { exchange:  string } ,
         config?:  any
       ):  promise < CryptoTrade > ;
  •    getLatestCryptoTrades (
         symbols:  array < string > ,
         options:  {  exchange:  string  }, 
         config?:  any
       ):  promise < map < string,  CryptoTrade > > ;

Quotes

  •    getCryptoQuotes (
         symbol:  string ,
         options:  GetCryptoQuotesParams, 
         config?:  any ,
       ):  AsyncGenerator < CryptoQuote,  

    void

    , stranger > ;
  •    getLatestCryptoQuote (
         symbol:  string ,
         options:  {  exchange:  string  } ,
         config?:  any ,
       ):  promise < CryptoQuote > ;
  •   getLatestCryptoQuotes (
       symbols:  array < string > ,
       options:  {  exchange:  string  } ,
       config?:  any ,
     ):  promise < map < drawstring,  CryptoQuote > > ;

Bars

  •     getCryptoBars (
         symbol:  chain ,
         options:  GetCryptoBarsParams, 
         config?:  any ,
       ):  AsyncGenerator < CryptoBar,  

    void

    , obscure > ;
  •     getLatestCryptoBar (
          symbol:  string ,
          options:  {  exchange:  string  }, 
          config?:  any ,
        ):  promise < CryptoBar > ;
  •    getLatestCryptoBars (
         symbols:  array < string > ,
         options:  {  exchange:  string  } ,
         config?:  any ,
       ):  promise < map < chain,  CryptoBar > > ;

XBBOs

  •    getLatestCryptoXBBO (
         symbol:  string ,
         options:  {  exchanges?:  array < string >  } ,
         config?:  any ,
       ):  promise < CryptoXBBO > ;
  •    getLatestCryptoXBBOs (
         symbols:  array < string > ,
         options:  {  exchanges?:  array < drawstring >  }, 
         config?:  any ,
       ):  predict < function < drawstring,  CryptoXBBO > > ;

Snapshots

  •    getCryptoSnapshot (
         symbol:  bowed stringed instrument ,
         options:   {  exchange:  string  } ,
         config?:  any ,
       ):  predict < CryptoSnapshot > ;

Websockets

You can use data websocket with or without a fund score .

Working with websocket

 const  websocket  =  alpaca. data_stream_v2 ;
 websocket. onConnect ( ( )  = >  {
   websocket. subscribeForTrades ( [ `` AAPL '' ] ) ;
 } ) ;
 websocket. onStateChange ( ( status )  = >  { 
   cabinet. log ( `` status : '',  condition ) ;
 } ) ;
 websocket. onError ( ( err )  = >  {
   console. log ( `` erroneousness : '',  stray ) ;
 } ) ;
 websocket. onStockTrade ( ( trade )  = >  {
   comfort. log ( `` Trade : '',  trade ) ;
 } ) ;
 websocket. connect ( ) ;
 status:  connecting
 status:  authenticating
 condition:  connected
 condition:  authenticated
 Trade:  {
   thyroxine:  't ',
   symbol:  'AAPL ',
   id:  68,
   Exchange:  'V ',
   price:  165.02,
   size:  50,
   Conditions: [  ' @ ',  'T ',  'I ' ],
   videotape:  'C ',
   Timestamp:  2022 - 04 - 19 T12 : 50: 29.214 omega
}
  • The websocket is created when you first create the Alpaca instance
  • const websocket = alpaca.data_stream_v2: Get the websocket client instance.
  • websocket.connect(): Connect to the Alpaca server using websocket.
  • websocket.onConnect(() => {}): all the following code will be executed after
    the user authentication. You can also subscribe and unsubscribe for data
    outside this function.
  • websocket.subscribeForTrades(["AAPL"]): Subscribe for trades data for the
    given symbol(s). You can do the same with quotes, bars, dailyBars, updatedBars, statuses and lulds.
  • websocket.onStockTrade((trade) => {}): Get the data by subscribing for the trade data event
    in JS/TS and process it inside this function.
  • websocket.unsubscribeFromTrades(["symbol"]): Unsubscribe from symbol(s).
  • websocket.onDisconnect(() => {}) and websocket.disconnect(): the function
    inside the onDisconnect will run when you disconnect then closes the connection
    between the client and server.

    Websocket client for real-time crypto and news data work the same. For a detailed example please take a look
    at this file.

reservoir : https://coinselected
Category : coin 4u

Leave a Reply

Your email address will not be published.