UNPKG

17 kBJavaScriptView Raw
1import t from"qs";import e from"isomorphic-unfetch";import s from"bottleneck";import a from"is-blob";import r from"isomorphic-ws";import i from"eventemitter3";function n(t,e,s,a){return new(s||(s=Promise))((function(r,i){function n(t){try{c(a.next(t))}catch(t){i(t)}}function o(t){try{c(a.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?r(t.value):(e=t.value,e instanceof s?e:new s((function(t){t(e)}))).then(n,o)}c((a=a.apply(t,e||[])).next())}))}function o(t){if(t)try{return Object.assign(Object.assign({},t),{raw:()=>t,created_at:new Date(t.created_at),updated_at:new Date(t.updated_at),submitted_at:new Date(t.submitted_at),filled_at:new Date(t.filled_at),expired_at:new Date(t.expired_at),canceled_at:new Date(t.canceled_at),failed_at:new Date(t.failed_at),replaced_at:new Date(t.replaced_at),qty:p(t.qty),filled_qty:p(t.filled_qty),type:t.type,side:t.side,time_in_force:t.time_in_force,limit_price:p(t.limit_price),stop_price:p(t.stop_price),filled_avg_price:p(t.filled_avg_price),status:t.status,legs:c(t.legs),trail_price:p(t.trail_price),trail_percent:p(t.trail_percent),hwm:p(t.hwm),order_class:t.order_class})}catch(t){throw new Error(`Order parsing failed. ${t.message}`)}}function c(t){return t?t.map((t=>o(t))):void 0}function d(t){if(t)try{return Object.assign(Object.assign({},t),{raw:()=>t,avg_entry_price:p(t.avg_entry_price),qty:p(t.qty),side:t.side,market_value:p(t.market_value),cost_basis:p(t.cost_basis),unrealized_pl:p(t.unrealized_pl),unrealized_plpc:p(t.unrealized_plpc),unrealized_intraday_pl:p(t.unrealized_intraday_pl),unrealized_intraday_plpc:p(t.unrealized_intraday_plpc),current_price:p(t.current_price),lastday_price:p(t.lastday_price),change_today:p(t.change_today)})}catch(t){throw new Error(`Position parsing failed. ${t.message}`)}}function u(t){if(t)try{return Object.assign(Object.assign({},t),{raw:()=>t,cum_qty:p(t.cum_qty),leaves_qty:p(t.leaves_qty),price:p(t.price),qty:p(t.qty),side:t.side,type:t.type})}catch(t){throw new Error(`TradeActivity parsing failed. ${t.message}`)}}function l(t){if(t)try{return Object.assign(Object.assign({},t),{raw:()=>t,net_amount:p(t.net_amount),qty:p(t.qty),per_share_amount:p(t.per_share_amount)})}catch(t){throw new Error(`NonTradeActivity parsing failed. ${t.message}`)}}function h(t){if(t)try{return Object.assign(Object.assign({},t),{raw:()=>t,latestTrade:t.latestTrade?Object.assign(Object.assign({},t.latestTrade),{t:new Date(t.latestTrade.t)}):null,latestQuote:t.latestQuote?Object.assign(Object.assign({},t.latestQuote),{t:new Date(t.latestQuote.t)}):null,minuteBar:t.minuteBar?Object.assign(Object.assign({},t.minuteBar),{t:new Date(t.minuteBar.t)}):null,dailyBar:t.dailyBar?Object.assign(Object.assign({},t.dailyBar),{t:new Date(t.dailyBar.t)}):null,prevDailyBar:t.prevDailyBar?Object.assign(Object.assign({},t.prevDailyBar),{t:new Date(t.prevDailyBar.t)}):null})}catch(t){throw new Error(`Snapshot parsing failed "${t.message}"`)}}function p(t){if(void 0===t||null==t)return t;const e=parseFloat(t);return Number.isNaN(e)?null:e}var m={account:function(t){if(t)try{return Object.assign(Object.assign({},t),{raw:()=>t,buying_power:p(t.buying_power),regt_buying_power:p(t.regt_buying_power),daytrading_buying_power:p(t.daytrading_buying_power),cash:p(t.cash),created_at:new Date(t.created_at),portfolio_value:p(t.portfolio_value),multiplier:p(t.multiplier),equity:p(t.equity),last_equity:p(t.last_equity),long_market_value:p(t.long_market_value),short_market_value:p(t.short_market_value),initial_margin:p(t.initial_margin),maintenance_margin:p(t.maintenance_margin),last_maintenance_margin:p(t.last_maintenance_margin),sma:p(t.sma),status:t.status})}catch(t){throw new Error(`Account parsing failed. ${t.message}`)}},activities:function(t){if(t)try{return t.map((t=>"FILL"===t.activity_type?u(t):l(t)))}catch(t){throw new Error(`Activity parsing failed. ${t.message}`)}},clock:function(t){if(t)try{return{raw:()=>t,timestamp:new Date(t.timestamp),is_open:t.is_open,next_open:new Date(t.next_open),next_close:new Date(t.next_close)}}catch(t){throw new Error(`Order parsing failed. ${t.message}`)}},nonTradeActivity:l,order:o,orders:c,canceled_orders:function(t){return t?t.map((t=>function(t){if(!t)return;let e=t.body;delete t.body;try{return Object.assign(Object.assign({},t),{order:Object.assign(Object.assign({},e),{raw:()=>e,created_at:new Date(e.created_at),updated_at:new Date(e.updated_at),submitted_at:new Date(e.submitted_at),filled_at:new Date(e.filled_at),expired_at:new Date(e.expired_at),canceled_at:new Date(e.canceled_at),failed_at:new Date(e.failed_at),replaced_at:new Date(e.replaced_at),qty:p(e.qty),filled_qty:p(e.filled_qty),type:e.type,side:e.side,time_in_force:e.time_in_force,limit_price:p(e.limit_price),stop_price:p(e.stop_price),filled_avg_price:p(e.filled_avg_price),status:e.status,legs:c(e.legs),trail_price:p(e.trail_price),trail_percent:p(e.trail_percent),hwm:p(e.hwm),order_class:e.order_class})})}catch(t){throw new Error(`Order parsing failed. ${t.message}`)}}(t))):void 0},position:d,positions:function(t){return t?t.map((t=>d(t))):void 0},tradeActivity:u,pageOfTrades:function(t){if(t)try{return{raw:()=>t,trades:(null==t.trades?[]:t.trades).map((t=>Object.assign(Object.assign({raw:()=>t},t),{t:new Date(t.t)}))),symbol:t.symbol,next_page_token:t.next_page_token}}catch(t){throw new Error(`PageOfTrades parsing failed "${t.message}"`)}},pageOfQuotes:function(t){if(t)try{return{raw:()=>t,quotes:(null==t.quotes?[]:t.quotes).map((t=>Object.assign(Object.assign({raw:()=>t},t),{t:new Date(t.t)}))),symbol:t.symbol,next_page_token:t.next_page_token}}catch(t){throw new Error(`PageOfTrades parsing failed "${t.message}"`)}},pageOfBars:function(t){if(t)try{return{raw:()=>t,bars:(null==t.bars?[]:t.bars).map((t=>Object.assign(Object.assign({raw:()=>t},t),{t:new Date(t.t)}))),symbol:t.symbol,next_page_token:t.next_page_token}}catch(t){throw new Error(`PageOfTrades parsing failed "${t.message}"`)}},snapshot:h,snapshots:function(t){let e={};for(let[s,a]of Object.entries(t))e[s]=h(a);return e},trade_update:function(t){if(t)return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({raw:()=>t,event:t.event,execution_id:t.execution_id,order:o(t.order)},t.event_id&&{event_id:p(t.event_id)}),t.at&&{at:new Date(t.at)}),t.timestamp&&{timestamp:new Date(t.timestamp)}),t.position_qty&&{position_qty:p(t.position_qty)}),t.price&&{price:p(t.price)}),t.qty&&{qty:p(t.qty)})},latestTrade:function(t){if(t)try{return Object.assign(Object.assign({},t),{raw:()=>t,trade:Object.assign(Object.assign({},t.trade),{t:new Date(t.trade.t)})})}catch(t){throw new Error(`Latest trade parsing failed. ${t.message}`)}}};const _={rest:{beta:"https://data.alpaca.markets/v1beta1",account:"https://api.alpaca.markets/v2",market_data_v2:"https://data.alpaca.markets/v2",market_data_v1:"https://data.alpaca.markets/v1"},websocket:{account:"wss://api.alpaca.markets/stream",market_data:(t="iex")=>`wss://stream.data.alpaca.markets/v2/${t}`}},y="undefined"!=typeof fetch?fetch:e;class b{constructor(t){if(this.params=t,this.baseURLs=_,this.limiter=new s({reservoir:200,reservoirRefreshAmount:200,reservoirRefreshInterval:6e4,maxConcurrent:1,minTime:200}),"endpoints"in t&&(this.baseURLs=Object.assign(_,t.endpoints)),"paper"in t.credentials||"key"in t.credentials&&t.credentials.key.startsWith("A")||(t.credentials.paper=!0),"access_token"in t.credentials&&("key"in t.credentials||"secret"in t.credentials))throw new Error("can't create client with both default and oauth credentials")}isAuthenticated(){return n(this,void 0,void 0,(function*(){try{return yield this.getAccount(),!0}catch(t){return!1}}))}getAccount(){return n(this,void 0,void 0,(function*(){return m.account(yield this.request({method:"GET",url:`${this.baseURLs.rest.account}/account`}))}))}getOrder(t){return n(this,void 0,void 0,(function*(){return m.order(yield this.request({method:"GET",url:`${this.baseURLs.rest.account}/orders/${t.order_id||t.client_order_id}`,data:{nested:t.nested}}))}))}getOrders(t={}){return n(this,void 0,void 0,(function*(){return m.orders(yield this.request({method:"GET",url:`${this.baseURLs.rest.account}/orders`,data:Object.assign(Object.assign({},t),{symbols:t.symbols?t.symbols.join(","):void 0})}))}))}placeOrder(t){return n(this,void 0,void 0,(function*(){return m.order(yield this.request({method:"POST",url:`${this.baseURLs.rest.account}/orders`,data:t}))}))}replaceOrder(t){return n(this,void 0,void 0,(function*(){return m.order(yield this.request({method:"PATCH",url:`${this.baseURLs.rest.account}/orders/${t.order_id}`,data:t}))}))}cancelOrder(t){return this.request({method:"DELETE",url:`${this.baseURLs.rest.account}/orders/${t.order_id}`,isJSON:!1})}cancelOrders(){return n(this,void 0,void 0,(function*(){return m.canceled_orders(yield this.request({method:"DELETE",url:`${this.baseURLs.rest.account}/orders`}))}))}getPosition(t){return n(this,void 0,void 0,(function*(){return m.position(yield this.request({method:"GET",url:`${this.baseURLs.rest.account}/positions/${t.symbol}`}))}))}getPositions(){return n(this,void 0,void 0,(function*(){return m.positions(yield this.request({method:"GET",url:`${this.baseURLs.rest.account}/positions`}))}))}closePosition(t){return n(this,void 0,void 0,(function*(){return m.order(yield this.request({method:"DELETE",url:`${this.baseURLs.rest.account}/positions/${t.symbol}`,data:t}))}))}closePositions(t){var e;return n(this,void 0,void 0,(function*(){return m.orders(yield this.request({method:"DELETE",url:`${this.baseURLs.rest.account}/positions?cancel_orders=${JSON.stringify(null!==(e=t.cancel_orders)&&void 0!==e&&e)}`}))}))}getAsset(t){return this.request({method:"GET",url:`${this.baseURLs.rest.account}/assets/${t.asset_id_or_symbol}`})}getAssets(t){return this.request({method:"GET",url:`${this.baseURLs.rest.account}/assets`,data:t})}getWatchlist(t){return this.request({method:"GET",url:`${this.baseURLs.rest.account}/watchlists/${t.uuid}`})}getWatchlists(){return this.request({method:"GET",url:`${this.baseURLs.rest.account}/watchlists`})}createWatchlist(t){return this.request({method:"POST",url:`${this.baseURLs.rest.account}/watchlists`,data:t})}updateWatchlist(t){return this.request({method:"PUT",url:`${this.baseURLs.rest.account}/watchlists/${t.uuid}`,data:t})}addToWatchlist(t){return this.request({method:"POST",url:`${this.baseURLs.rest.account}/watchlists/${t.uuid}`,data:t})}removeFromWatchlist(t){return this.request({method:"DELETE",url:`${this.baseURLs.rest.account}/watchlists/${t.uuid}/${t.symbol}`})}deleteWatchlist(t){return this.request({method:"DELETE",url:`${this.baseURLs.rest.account}/watchlists/${t.uuid}`})}getCalendar(t){return this.request({method:"GET",url:`${this.baseURLs.rest.account}/calendar`,data:t})}getNews(t){return"symbols"in t&&Array.isArray(t.symbols)&&(t.symbols=t.symbols.join(",")),this.request({method:"GET",url:`${this.baseURLs.rest.beta}/news`,data:t})}getClock(){return n(this,void 0,void 0,(function*(){return m.clock(yield this.request({method:"GET",url:`${this.baseURLs.rest.account}/clock`}))}))}getAccountConfigurations(){return this.request({method:"GET",url:`${this.baseURLs.rest.account}/account/configurations`})}updateAccountConfigurations(t){return this.request({method:"PATCH",url:`${this.baseURLs.rest.account}/account/configurations`,data:t})}getAccountActivities(t){return n(this,void 0,void 0,(function*(){return t.activity_types&&Array.isArray(t.activity_types)&&(t.activity_types=t.activity_types.join(",")),m.activities(yield this.request({method:"GET",url:`${this.baseURLs.rest.account}/account/activities${t.activity_type?"/".concat(t.activity_type):""}`,data:Object.assign(Object.assign({},t),{activity_type:void 0})}))}))}getPortfolioHistory(t){return this.request({method:"GET",url:`${this.baseURLs.rest.account}/account/portfolio/history`,data:t})}getBars_v1(t){return n(this,void 0,void 0,(function*(){const e=Object.assign(Object.assign({},t),{symbols:t.symbols.join(",")});return yield this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v1}/bars/${t.timeframe}`,data:e})}))}getLastTrade_v1(t){return n(this,void 0,void 0,(function*(){return yield this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v1}/last/stocks/${t.symbol}`})}))}getLastQuote_v1(t){return n(this,void 0,void 0,(function*(){return yield this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v1}/last_quote/stocks/${t.symbol}`})}))}getTrades(t){return n(this,void 0,void 0,(function*(){return m.pageOfTrades(yield this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v2}/stocks/${t.symbol}/trades`,data:Object.assign(Object.assign({},t),{symbol:void 0})}))}))}getQuotes(t){return n(this,void 0,void 0,(function*(){return m.pageOfQuotes(yield this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v2}/stocks/${t.symbol}/quotes`,data:Object.assign(Object.assign({},t),{symbol:void 0})}))}))}getBars(t){return n(this,void 0,void 0,(function*(){return m.pageOfBars(yield this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v2}/stocks/${t.symbol}/bars`,data:Object.assign(Object.assign({},t),{symbol:void 0})}))}))}getLatestTrade({symbol:e,feed:s,limit:a}){return n(this,void 0,void 0,(function*(){let r="";return(s||a)&&(r="?".concat(t.stringify({feed:s,limit:a}))),m.latestTrade(yield this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v2}/stocks/${e}/trades/latest`.concat(r)}))}))}getSnapshot(t){return n(this,void 0,void 0,(function*(){return m.snapshot(yield this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v2}/stocks/${t.symbol}/snapshot`}))}))}getSnapshots(t){return n(this,void 0,void 0,(function*(){return m.snapshots(yield this.request({method:"GET",url:`${this.baseURLs.rest.market_data_v2}/stocks/snapshots?symbols=${t.symbols.join(",")}`}))}))}request(e){return n(this,void 0,void 0,(function*(){let s={};"access_token"in this.params.credentials?s.Authorization=`Bearer ${this.params.credentials.access_token}`:(s["APCA-API-KEY-ID"]=this.params.credentials.key,s["APCA-API-SECRET-KEY"]=this.params.credentials.secret),this.params.credentials.paper&&(e.url=e.url.replace("api.","paper-api."));let a="";if(e.data){for(let[t,s]of Object.entries(e.data))s instanceof Date&&(e.data[t]=s.toISOString());["POST","PATCH","PUT"].includes(e.method)||(a="?".concat(t.stringify(e.data)),e.data=void 0)}const r=()=>y(e.url.concat(a),{method:e.method,headers:s,body:JSON.stringify(e.data)}),i=this.params.rate_limit?()=>this.limiter.schedule(r):r;let n,o={};try{if(n=yield i(),null!=e.isJSON&&!e.isJSON)return n.ok;o=yield n.json()}catch(t){throw console.error(t),o}if("code"in o||"message"in o)throw o;return o}))}}class g extends i{constructor(t){switch(super(),this.params=t,this.baseURLs=_,"endpoints"in t&&(this.baseURLs=Object.assign(_,t.endpoints)),"paper"in t.credentials||"key"in t.credentials&&t.credentials.key.startsWith("A")||(t.credentials.paper=!0),t.type){case"account":this.host=t.credentials.paper?this.baseURLs.websocket.account.replace("api.","paper-api."):this.baseURLs.websocket.account;break;case"market_data":this.host=this.baseURLs.websocket.market_data(this.params.source);break;default:this.host="unknown"}this.connection=new r(this.host),this.connection.onopen=()=>{let e={};switch(this.params.type){case"account":e={action:"authenticate",data:{key_id:t.credentials.key,secret_key:t.credentials.secret}};break;case"market_data":e=Object.assign({action:"auth"},t.credentials)}this.connection.send(JSON.stringify(e)),this.emit("open",this)},this.connection.onclose=()=>this.emit("close",this),this.connection.onmessage=t=>n(this,void 0,void 0,(function*(){let e=t.data;a(e)?e=yield t.data.text():e instanceof ArrayBuffer&&(e=String.fromCharCode(...new Uint8Array(t.data)));let s=JSON.parse(e);("account"==this.params.type?[s]:s).forEach((t=>{this.emit("message",t),("T"in t&&"authenticated"==t.msg||"stream"in t&&"authorization"==t.stream&&"authorized"==t.data.status)&&(this.authenticated=!0,this.emit("authenticated",this)),"stream"in t&&"trade_updates"==t.stream&&this.emit("trade_updates",m.trade_update(t.data));const e={success:"success",subscription:"subscription",error:"error",t:"trade",q:"quote",b:"bar"};"T"in t&&this.emit(e[t.T.split(".")[0]],t)}))})),this.connection.onerror=t=>{this.emit("error",t)}}getConnection(){return this.connection}subscribe(t,e=[]){switch(this.params.type){case"account":this.send(JSON.stringify({action:"listen",data:{streams:[t]}}));break;case"market_data":let s={action:"subscribe"};s[t]=e,this.send(JSON.stringify(s))}return this}unsubscribe(t,e=[]){switch(this.params.type){case"account":this.send(JSON.stringify({action:"unlisten",data:{streams:[t]}}));break;case"market_data":let s={action:"unsubscribe"};s[t]=e,this.send(JSON.stringify(s))}return this}send(t){if(!this.authenticated)throw new Error("not authenticated");return"object"==typeof t&&(t=JSON.stringify(t)),this.connection.send(t),this}}var f={AlpacaClient:b,AlpacaStream:g};export{b as AlpacaClient,g as AlpacaStream,f as default};