@master-chief/alpaca
Advanced tools
Comparing version 4.4.1 to 4.4.4
@@ -1,2 +0,2 @@ | ||
import { Account, Order, Position, Asset, Watchlist, Calendar, Clock, AccountConfigurations, PortfolioHistory, Bar, LastQuote, LastTrade, Activity, DefaultCredentials, OAuthCredentials } from './entities.js'; | ||
import { Account, Order, Position, Asset, Watchlist, Calendar, Clock, AccountConfigurations, PortfolioHistory, Bar, LastQuote, LastTrade, Activity, DefaultCredentials, OAuthCredentials, OrderCancelation } from './entities.js'; | ||
import { GetOrder, GetOrders, PlaceOrder, ReplaceOrder, CancelOrder, GetPosition, ClosePosition, GetAsset, GetAssets, GetWatchList, CreateWatchList, UpdateWatchList, AddToWatchList, RemoveFromWatchList, DeleteWatchList, GetCalendar, UpdateAccountConfigurations, GetAccountActivities, GetPortfolioHistory, GetBars, GetLastTrade, GetLastQuote } from './params.js'; | ||
@@ -20,3 +20,3 @@ export declare class AlpacaClient { | ||
cancelOrder(params: CancelOrder): Promise<Boolean>; | ||
cancelOrders(): Promise<Order[]>; | ||
cancelOrders(): Promise<OrderCancelation[]>; | ||
getPosition(params: GetPosition): Promise<Position>; | ||
@@ -23,0 +23,0 @@ getPositions(): Promise<Position[]>; |
@@ -460,2 +460,18 @@ /** | ||
/** | ||
* The parsed result of an order cancelation request. | ||
*/ | ||
export interface OrderCancelation { | ||
id: string; | ||
status: number; | ||
order: Order; | ||
} | ||
/** | ||
* The id, http status code and order as part of the cancel all orders request. | ||
*/ | ||
export interface RawOrderCancelation { | ||
id: string; | ||
status: number; | ||
body: RawOrder; | ||
} | ||
/** | ||
* The order entity with unparsed fields, exactly as Alpaca provides it. | ||
@@ -462,0 +478,0 @@ * We encourage you to use the Order interface, which has many of these fields parsed. |
@@ -10,3 +10,3 @@ export { AlpacaClient } from './client.js'; | ||
export default _default; | ||
export { Account, Order, Position, Asset, Watchlist, Calendar, Clock, DefaultCredentials, OAuthCredentials, AccountConfigurations, NonTradeActivity, TradeActivity, Activity, PortfolioHistory, Bar, LastQuote, LastTrade, } from './entities'; | ||
export { Account, Order, OrderCancelation, Position, Asset, Watchlist, Calendar, Clock, DefaultCredentials, OAuthCredentials, AccountConfigurations, NonTradeActivity, TradeActivity, Activity, PortfolioHistory, Bar, LastQuote, LastTrade, } from './entities'; | ||
export { GetOrder, GetOrders, PlaceOrder, ReplaceOrder, CancelOrder, GetPosition, ClosePosition, GetAsset, GetAssets, GetWatchList, CreateWatchList, UpdateWatchList, AddToWatchList, RemoveFromWatchList, DeleteWatchList, GetCalendar, UpdateAccountConfigurations, GetAccountActivities, GetPortfolioHistory, GetBars, GetLastTrade, GetLastQuote, } from './params'; |
@@ -1,2 +0,2 @@ | ||
import { Account, RawAccount, RawOrder, Order, RawPosition, Position, RawTradeActivity, TradeActivity, RawNonTradeActivity, NonTradeActivity, RawActivity, Activity, RawClock, Clock } from './entities.js'; | ||
import { Account, RawAccount, RawOrder, Order, RawPosition, Position, RawTradeActivity, TradeActivity, RawNonTradeActivity, NonTradeActivity, RawActivity, Activity, RawClock, Clock, RawOrderCancelation, OrderCancelation } from './entities.js'; | ||
declare function account(rawAccount: RawAccount): Account; | ||
@@ -6,2 +6,3 @@ declare function clock(rawClock: RawClock): Clock; | ||
declare function orders(rawOrders: RawOrder[]): Order[]; | ||
declare function canceled_orders(rawOrderCancelations: RawOrderCancelation[]): OrderCancelation[]; | ||
declare function position(rawPosition: RawPosition): Position; | ||
@@ -19,2 +20,3 @@ declare function positions(rawPositions: RawPosition[]): Position[]; | ||
orders: typeof orders; | ||
canceled_orders: typeof canceled_orders; | ||
position: typeof position; | ||
@@ -21,0 +23,0 @@ positions: typeof positions; |
/*! | ||
* alpaca@4.4.1 | ||
* alpaca@4.4.4 | ||
* released under the permissive ISC license | ||
@@ -91,2 +91,20 @@ */ | ||
} | ||
function canceled_order(input) { | ||
if (!input) { | ||
return undefined; | ||
} | ||
let order = input.body; | ||
delete input.body; | ||
try { | ||
return Object.assign(Object.assign({}, input), { order: Object.assign(Object.assign({}, order), { raw: () => order, created_at: new Date(order.created_at), updated_at: new Date(order.updated_at), submitted_at: new Date(order.submitted_at), filled_at: new Date(order.filled_at), expired_at: new Date(order.expired_at), canceled_at: new Date(order.canceled_at), failed_at: new Date(order.failed_at), replaced_at: new Date(order.replaced_at), qty: number(order.qty), filled_qty: number(order.filled_qty), type: order.type, side: order.side, time_in_force: order.time_in_force, limit_price: number(order.limit_price), stop_price: number(order.stop_price), filled_avg_price: number(order.filled_avg_price), status: order.status, legs: orders(order.legs), trail_price: number(order.trail_price), trail_percent: number(order.trail_percent), hwm: number(order.hwm) }) }); | ||
} | ||
catch (err) { | ||
throw new Error(`Order parsing failed. ${err.message}`); | ||
} | ||
} | ||
function canceled_orders(rawOrderCancelations) { | ||
return rawOrderCancelations | ||
? rawOrderCancelations.map((value) => canceled_order(value)) | ||
: undefined; | ||
} | ||
function position(rawPosition) { | ||
@@ -153,2 +171,3 @@ if (!rawPosition) { | ||
orders, | ||
canceled_orders, | ||
position, | ||
@@ -222,3 +241,3 @@ positions, | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return parse.orders(yield this.request('DELETE', urls.rest.account, `orders`)); | ||
return parse.canceled_orders(yield this.request('DELETE', urls.rest.account, `orders`)); | ||
}); | ||
@@ -225,0 +244,0 @@ } |
@@ -1,1 +0,1 @@ | ||
import t from"bottleneck";import e from"qs";import r from"isomorphic-unfetch";import i from"isomorphic-ws";import s from"eventemitter3";function a(t,e,r,i){return new(r||(r=Promise))((function(s,a){function n(t){try{o(i.next(t))}catch(t){a(t)}}function c(t){try{o(i.throw(t))}catch(t){a(t)}}function o(t){var e;t.done?s(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(n,c)}o((i=i.apply(t,e||[])).next())}))}var n={rest:{account:"https://api.alpaca.markets/v2",market_data:"https://data.alpaca.markets/v1"},websocket:{account:"wss://api.alpaca.markets/stream",account_paper:"wss://paper-api.alpaca.markets/stream",market_data:"wss://data.alpaca.markets/stream"}};function c(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:h(t.qty),filled_qty:h(t.filled_qty),type:t.type,side:t.side,time_in_force:t.time_in_force,limit_price:h(t.limit_price),stop_price:h(t.stop_price),filled_avg_price:h(t.filled_avg_price),status:t.status,legs:o(t.legs),trail_price:h(t.trail_price),trail_percent:h(t.trail_percent),hwm:h(t.hwm)})}catch(t){throw new Error(`Order parsing failed. ${t.message}`)}}function o(t){return t?t.map((t=>c(t))):void 0}function u(t){if(t)try{return Object.assign(Object.assign({},t),{raw:()=>t,avg_entry_price:h(t.avg_entry_price),qty:h(t.qty),side:t.side,market_value:h(t.market_value),cost_basis:h(t.cost_basis),unrealized_pl:h(t.unrealized_pl),unrealized_plpc:h(t.unrealized_plpc),unrealized_intraday_pl:h(t.unrealized_intraday_pl),unrealized_intraday_plpc:h(t.unrealized_intraday_plpc),current_price:h(t.current_price),lastday_price:h(t.lastday_price),change_today:h(t.change_today)})}catch(t){throw new Error(`Position parsing failed. ${t.message}`)}}function d(t){if(t)try{return Object.assign(Object.assign({},t),{raw:()=>t,cum_qty:h(t.cum_qty),leaves_qty:h(t.leaves_qty),price:h(t.price),qty:h(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:h(t.net_amount),qty:h(t.qty),per_share_amount:h(t.per_share_amount)})}catch(t){throw new Error(`NonTradeActivity parsing failed. ${t.message}`)}}function h(t){return void 0===t?t:parseFloat(t)}var p={account:function(t){if(t)try{return Object.assign(Object.assign({},t),{raw:()=>t,buying_power:h(t.buying_power),regt_buying_power:h(t.regt_buying_power),daytrading_buying_power:h(t.daytrading_buying_power),cash:h(t.cash),created_at:new Date(t.created_at),portfolio_value:h(t.portfolio_value),multiplier:h(t.multiplier),equity:h(t.equity),last_equity:h(t.last_equity),long_market_value:h(t.long_market_value),short_market_value:h(t.short_market_value),initial_margin:h(t.initial_margin),maintenance_margin:h(t.maintenance_margin),last_maintenance_margin:h(t.last_maintenance_margin),sma:h(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?d(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:c,orders:o,position:u,positions:function(t){return t?t.map((t=>u(t))):void 0},tradeActivity:d};const _="undefined"!=typeof fetch?fetch:r;class m{constructor(e){if(this.params=e,this.limiter=new t({reservoir:200,reservoirRefreshAmount:200,reservoirRefreshInterval:6e4,maxConcurrent:1,minTime:200}),"paper"in e.credentials||"key"in e.credentials&&e.credentials.key.startsWith("A")||(e.credentials.paper=!0),"access_token"in e.credentials&&("key"in e.credentials||"secret"in e.credentials))throw new Error("can't create client with both default and oauth credentials")}isAuthenticated(){return a(this,void 0,void 0,(function*(){try{return yield this.getAccount(),!0}catch(t){return!1}}))}getAccount(){return a(this,void 0,void 0,(function*(){return p.account(yield this.request("GET",n.rest.account,"account"))}))}getOrder(t){return a(this,void 0,void 0,(function*(){return p.order(yield this.request("GET",n.rest.account,`orders/${t.order_id||t.client_order_id}?${e.stringify({nested:t.nested})}`))}))}getOrders(t){return a(this,void 0,void 0,(function*(){return p.orders(yield this.request("GET",n.rest.account,`orders?${e.stringify(t)}`))}))}placeOrder(t){return a(this,void 0,void 0,(function*(){return p.order(yield this.request("POST",n.rest.account,"orders",t))}))}replaceOrder(t){return a(this,void 0,void 0,(function*(){return p.order(yield this.request("PATCH",n.rest.account,`orders/${t.order_id}`,t))}))}cancelOrder(t){return this.request("DELETE",n.rest.account,`orders/${t.order_id}`,void 0,!1)}cancelOrders(){return a(this,void 0,void 0,(function*(){return p.orders(yield this.request("DELETE",n.rest.account,"orders"))}))}getPosition(t){return a(this,void 0,void 0,(function*(){return p.position(yield this.request("GET",n.rest.account,`positions/${t.symbol}`))}))}getPositions(){return a(this,void 0,void 0,(function*(){return p.positions(yield this.request("GET",n.rest.account,"positions"))}))}closePosition(t){return a(this,void 0,void 0,(function*(){return p.order(yield this.request("DELETE",n.rest.account,`positions/${t.symbol}`))}))}closePositions(){return a(this,void 0,void 0,(function*(){return p.orders(yield this.request("DELETE",n.rest.account,"positions"))}))}getAsset(t){return this.request("GET",n.rest.account,`assets/${t.asset_id_or_symbol}`)}getAssets(t){return this.request("GET",n.rest.account,`assets?${e.stringify(t)}`)}getWatchlist(t){return this.request("GET",n.rest.account,`watchlists/${t.uuid}`)}getWatchlists(){return this.request("GET",n.rest.account,"watchlists")}createWatchlist(t){return this.request("POST",n.rest.account,"watchlists",t)}updateWatchlist(t){return this.request("PUT",n.rest.account,`watchlists/${t.uuid}`,t)}addToWatchlist(t){return this.request("POST",n.rest.account,`watchlists/${t.uuid}`,t)}removeFromWatchlist(t){return this.request("DELETE",n.rest.account,`watchlists/${t.uuid}/${t.symbol}`,void 0,!1)}deleteWatchlist(t){return this.request("DELETE",n.rest.account,`watchlists/${t.uuid}`,void 0,!1)}getCalendar(t){return this.request("GET",n.rest.account,`calendar?${e.stringify(t)}`)}getClock(){return a(this,void 0,void 0,(function*(){return p.clock(yield this.request("GET",n.rest.account,"clock"))}))}getAccountConfigurations(){return this.request("GET",n.rest.account,"account/configurations")}updateAccountConfigurations(t){return this.request("PATCH",n.rest.account,"account/configurations",t)}getAccountActivities(t){return a(this,void 0,void 0,(function*(){return t.activity_types&&Array.isArray(t.activity_types)&&(t.activity_types=t.activity_types.join(",")),p.activities(yield this.request("GET",n.rest.account,`account/activities${t.activity_type?"/".concat(t.activity_type):""}?${e.stringify(t)}`))}))}getPortfolioHistory(t){return this.request("GET",n.rest.account,`account/portfolio/history?${e.stringify(t)}`)}getBars(t){const r=Object.assign(Object.assign({},t),{symbols:t.symbols.join(",")});return this.request("GET",n.rest.market_data,`bars/${t.timeframe}?${e.stringify(r)}`)}getLastTrade(t){return this.request("GET",n.rest.market_data,`last/stocks/${t.symbol}`)}getLastQuote(t){return this.request("GET",n.rest.market_data,`last_quote/stocks/${t.symbol}`)}request(t,e,r,i,s=!0){return a(this,void 0,void 0,(function*(){let a={};if("access_token"in this.params.credentials?a.Authorization=`Bearer ${this.params.credentials.access_token}`:(a["APCA-API-KEY-ID"]=this.params.credentials.key,a["APCA-API-SECRET-KEY"]=this.params.credentials.secret,this.params.credentials.paper&&e==n.rest.account&&(e=n.rest.account.replace("api.","paper-api."))),i)for(let[t,e]of Object.entries(i))e instanceof Date&&(i[t]=e.toISOString());const c=()=>_(`${e}/${r}`,{method:t,headers:a,body:JSON.stringify(i)}),o=this.params.rate_limit?()=>this.limiter.schedule(c):c;let u,d={};try{if(u=yield o(),!s)return u.ok;d=yield u.json()}catch(t){throw console.error(t),d}if("code"in d&&"message"in d)throw d;return d}))}}class y extends s{constructor(t){switch(super(),this.params=t,this.subscriptions=[],this.authenticated=!1,t.stream){case"account":this.host=t.credentials.key.startsWith("PK")?n.websocket.account_paper:n.websocket.account;break;case"market_data":this.host=n.websocket.market_data;break;default:this.host="unknown"}this.connection=new i(this.host),this.connection.onopen=()=>{this.authenticated||this.connection.send(JSON.stringify({action:"authenticate",data:{key_id:t.credentials.key,secret_key:t.credentials.secret}})),this.emit("open",this)},this.connection.onclose=()=>this.emit("close",this),this.connection.onmessage=t=>{const e=JSON.parse(t.data);if("stream"in e&&"authorization"==e.stream){if("authorized"!=e.data.status)throw this.connection.close(),new Error("There was an error in authorizing your websocket connection. Object received: "+JSON.stringify(e,null,2));this.authenticated=!0,this.emit("authenticated",this),console.log("Connected to the websocket.")}if(this.emit("message",e),"stream"in e){const t={trade_updates:"trade_updates",account_updates:"account_updates",T:"trade",Q:"quote",AM:"aggregate_minute"};this.emit(t[e.stream.split(".")[0]],e.data)}},this.connection.onerror=t=>{this.emit("error",t)}}on(t,e){return super.on(t,e)}send(t){if(!this.authenticated)throw new Error("You can't send a message until you are authenticated!");return"object"==typeof t&&(t=JSON.stringify(t)),this.connection.send(t),this}subscribe(t){return this.subscriptions.push(...t),this.send(JSON.stringify({action:"listen",data:{streams:t}}))}unsubscribe(t){for(let e=0,r=this.subscriptions.length;e<r;e++)t.includes(this.subscriptions[e])&&this.subscriptions.splice(e,1);return this.send(JSON.stringify({action:"unlisten",data:{streams:t}}))}}var f={AlpacaClient:m,AlpacaStream:y};export default f;export{m as AlpacaClient,y as AlpacaStream}; | ||
import t from"bottleneck";import e from"qs";import r from"isomorphic-unfetch";import i from"isomorphic-ws";import s from"eventemitter3";function a(t,e,r,i){return new(r||(r=Promise))((function(s,a){function n(t){try{o(i.next(t))}catch(t){a(t)}}function c(t){try{o(i.throw(t))}catch(t){a(t)}}function o(t){var e;t.done?s(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(n,c)}o((i=i.apply(t,e||[])).next())}))}var n={rest:{account:"https://api.alpaca.markets/v2",market_data:"https://data.alpaca.markets/v1"},websocket:{account:"wss://api.alpaca.markets/stream",account_paper:"wss://paper-api.alpaca.markets/stream",market_data:"wss://data.alpaca.markets/stream"}};function c(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:o(t.legs),trail_price:p(t.trail_price),trail_percent:p(t.trail_percent),hwm:p(t.hwm)})}catch(t){throw new Error(`Order parsing failed. ${t.message}`)}}function o(t){return t?t.map((t=>c(t))):void 0}function u(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 d(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 p(t){return void 0===t?t:parseFloat(t)}var _={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?d(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:c,orders:o,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:o(e.legs),trail_price:p(e.trail_price),trail_percent:p(e.trail_percent),hwm:p(e.hwm)})})}catch(t){throw new Error(`Order parsing failed. ${t.message}`)}}(t))):void 0},position:u,positions:function(t){return t?t.map((t=>u(t))):void 0},tradeActivity:d};const h="undefined"!=typeof fetch?fetch:r;class m{constructor(e){if(this.params=e,this.limiter=new t({reservoir:200,reservoirRefreshAmount:200,reservoirRefreshInterval:6e4,maxConcurrent:1,minTime:200}),"paper"in e.credentials||"key"in e.credentials&&e.credentials.key.startsWith("A")||(e.credentials.paper=!0),"access_token"in e.credentials&&("key"in e.credentials||"secret"in e.credentials))throw new Error("can't create client with both default and oauth credentials")}isAuthenticated(){return a(this,void 0,void 0,(function*(){try{return yield this.getAccount(),!0}catch(t){return!1}}))}getAccount(){return a(this,void 0,void 0,(function*(){return _.account(yield this.request("GET",n.rest.account,"account"))}))}getOrder(t){return a(this,void 0,void 0,(function*(){return _.order(yield this.request("GET",n.rest.account,`orders/${t.order_id||t.client_order_id}?${e.stringify({nested:t.nested})}`))}))}getOrders(t){return a(this,void 0,void 0,(function*(){return _.orders(yield this.request("GET",n.rest.account,`orders?${e.stringify(t)}`))}))}placeOrder(t){return a(this,void 0,void 0,(function*(){return _.order(yield this.request("POST",n.rest.account,"orders",t))}))}replaceOrder(t){return a(this,void 0,void 0,(function*(){return _.order(yield this.request("PATCH",n.rest.account,`orders/${t.order_id}`,t))}))}cancelOrder(t){return this.request("DELETE",n.rest.account,`orders/${t.order_id}`,void 0,!1)}cancelOrders(){return a(this,void 0,void 0,(function*(){return _.canceled_orders(yield this.request("DELETE",n.rest.account,"orders"))}))}getPosition(t){return a(this,void 0,void 0,(function*(){return _.position(yield this.request("GET",n.rest.account,`positions/${t.symbol}`))}))}getPositions(){return a(this,void 0,void 0,(function*(){return _.positions(yield this.request("GET",n.rest.account,"positions"))}))}closePosition(t){return a(this,void 0,void 0,(function*(){return _.order(yield this.request("DELETE",n.rest.account,`positions/${t.symbol}`))}))}closePositions(){return a(this,void 0,void 0,(function*(){return _.orders(yield this.request("DELETE",n.rest.account,"positions"))}))}getAsset(t){return this.request("GET",n.rest.account,`assets/${t.asset_id_or_symbol}`)}getAssets(t){return this.request("GET",n.rest.account,`assets?${e.stringify(t)}`)}getWatchlist(t){return this.request("GET",n.rest.account,`watchlists/${t.uuid}`)}getWatchlists(){return this.request("GET",n.rest.account,"watchlists")}createWatchlist(t){return this.request("POST",n.rest.account,"watchlists",t)}updateWatchlist(t){return this.request("PUT",n.rest.account,`watchlists/${t.uuid}`,t)}addToWatchlist(t){return this.request("POST",n.rest.account,`watchlists/${t.uuid}`,t)}removeFromWatchlist(t){return this.request("DELETE",n.rest.account,`watchlists/${t.uuid}/${t.symbol}`,void 0,!1)}deleteWatchlist(t){return this.request("DELETE",n.rest.account,`watchlists/${t.uuid}`,void 0,!1)}getCalendar(t){return this.request("GET",n.rest.account,`calendar?${e.stringify(t)}`)}getClock(){return a(this,void 0,void 0,(function*(){return _.clock(yield this.request("GET",n.rest.account,"clock"))}))}getAccountConfigurations(){return this.request("GET",n.rest.account,"account/configurations")}updateAccountConfigurations(t){return this.request("PATCH",n.rest.account,"account/configurations",t)}getAccountActivities(t){return a(this,void 0,void 0,(function*(){return t.activity_types&&Array.isArray(t.activity_types)&&(t.activity_types=t.activity_types.join(",")),_.activities(yield this.request("GET",n.rest.account,`account/activities${t.activity_type?"/".concat(t.activity_type):""}?${e.stringify(t)}`))}))}getPortfolioHistory(t){return this.request("GET",n.rest.account,`account/portfolio/history?${e.stringify(t)}`)}getBars(t){const r=Object.assign(Object.assign({},t),{symbols:t.symbols.join(",")});return this.request("GET",n.rest.market_data,`bars/${t.timeframe}?${e.stringify(r)}`)}getLastTrade(t){return this.request("GET",n.rest.market_data,`last/stocks/${t.symbol}`)}getLastQuote(t){return this.request("GET",n.rest.market_data,`last_quote/stocks/${t.symbol}`)}request(t,e,r,i,s=!0){return a(this,void 0,void 0,(function*(){let a={};if("access_token"in this.params.credentials?a.Authorization=`Bearer ${this.params.credentials.access_token}`:(a["APCA-API-KEY-ID"]=this.params.credentials.key,a["APCA-API-SECRET-KEY"]=this.params.credentials.secret,this.params.credentials.paper&&e==n.rest.account&&(e=n.rest.account.replace("api.","paper-api."))),i)for(let[t,e]of Object.entries(i))e instanceof Date&&(i[t]=e.toISOString());const c=()=>h(`${e}/${r}`,{method:t,headers:a,body:JSON.stringify(i)}),o=this.params.rate_limit?()=>this.limiter.schedule(c):c;let u,d={};try{if(u=yield o(),!s)return u.ok;d=yield u.json()}catch(t){throw console.error(t),d}if("code"in d&&"message"in d)throw d;return d}))}}class y extends s{constructor(t){switch(super(),this.params=t,this.subscriptions=[],this.authenticated=!1,t.stream){case"account":this.host=t.credentials.key.startsWith("PK")?n.websocket.account_paper:n.websocket.account;break;case"market_data":this.host=n.websocket.market_data;break;default:this.host="unknown"}this.connection=new i(this.host),this.connection.onopen=()=>{this.authenticated||this.connection.send(JSON.stringify({action:"authenticate",data:{key_id:t.credentials.key,secret_key:t.credentials.secret}})),this.emit("open",this)},this.connection.onclose=()=>this.emit("close",this),this.connection.onmessage=t=>{const e=JSON.parse(t.data);if("stream"in e&&"authorization"==e.stream){if("authorized"!=e.data.status)throw this.connection.close(),new Error("There was an error in authorizing your websocket connection. Object received: "+JSON.stringify(e,null,2));this.authenticated=!0,this.emit("authenticated",this),console.log("Connected to the websocket.")}if(this.emit("message",e),"stream"in e){const t={trade_updates:"trade_updates",account_updates:"account_updates",T:"trade",Q:"quote",AM:"aggregate_minute"};this.emit(t[e.stream.split(".")[0]],e.data)}},this.connection.onerror=t=>{this.emit("error",t)}}on(t,e){return super.on(t,e)}send(t){if(!this.authenticated)throw new Error("You can't send a message until you are authenticated!");return"object"==typeof t&&(t=JSON.stringify(t)),this.connection.send(t),this}subscribe(t){return this.subscriptions.push(...t),this.send(JSON.stringify({action:"listen",data:{streams:t}}))}unsubscribe(t){for(let e=0,r=this.subscriptions.length;e<r;e++)t.includes(this.subscriptions[e])&&this.subscriptions.splice(e,1);return this.send(JSON.stringify({action:"unlisten",data:{streams:t}}))}}var f={AlpacaClient:m,AlpacaStream:y};export default f;export{m as AlpacaClient,y as AlpacaStream}; |
@@ -60,3 +60,3 @@ import Bottleneck from 'bottleneck'; | ||
async cancelOrders() { | ||
return parse.orders(await this.request('DELETE', urls.rest.account, `orders`)); | ||
return parse.canceled_orders(await this.request('DELETE', urls.rest.account, `orders`)); | ||
} | ||
@@ -63,0 +63,0 @@ async getPosition(params) { |
@@ -86,2 +86,48 @@ function account(rawAccount) { | ||
} | ||
function canceled_order(input) { | ||
if (!input) { | ||
return undefined; | ||
} | ||
let order = input.body; | ||
// we don't want this field anymore | ||
delete input.body; | ||
try { | ||
return { | ||
...input, | ||
order: { | ||
...order, | ||
raw: () => order, | ||
created_at: new Date(order.created_at), | ||
updated_at: new Date(order.updated_at), | ||
submitted_at: new Date(order.submitted_at), | ||
filled_at: new Date(order.filled_at), | ||
expired_at: new Date(order.expired_at), | ||
canceled_at: new Date(order.canceled_at), | ||
failed_at: new Date(order.failed_at), | ||
replaced_at: new Date(order.replaced_at), | ||
qty: number(order.qty), | ||
filled_qty: number(order.filled_qty), | ||
type: order.type, | ||
side: order.side, | ||
time_in_force: order.time_in_force, | ||
limit_price: number(order.limit_price), | ||
stop_price: number(order.stop_price), | ||
filled_avg_price: number(order.filled_avg_price), | ||
status: order.status, | ||
legs: orders(order.legs), | ||
trail_price: number(order.trail_price), | ||
trail_percent: number(order.trail_percent), | ||
hwm: number(order.hwm), | ||
}, | ||
}; | ||
} | ||
catch (err) { | ||
throw new Error(`Order parsing failed. ${err.message}`); | ||
} | ||
} | ||
function canceled_orders(rawOrderCancelations) { | ||
return rawOrderCancelations | ||
? rawOrderCancelations.map((value) => canceled_order(value)) | ||
: undefined; | ||
} | ||
function position(rawPosition) { | ||
@@ -178,2 +224,3 @@ if (!rawPosition) { | ||
orders, | ||
canceled_orders, | ||
position, | ||
@@ -180,0 +227,0 @@ positions, |
{ | ||
"name": "@master-chief/alpaca", | ||
"version": "4.4.1", | ||
"version": "4.4.4", | ||
"description": "A TypeScript Node.js library for the https://alpaca.markets REST API and WebSocket streams.", | ||
@@ -5,0 +5,0 @@ "author": "117", |
@@ -29,2 +29,4 @@ import Bottleneck from 'bottleneck' | ||
OAuthCredentials, | ||
OrderCancelation, | ||
RawOrderCancelation, | ||
} from './entities.js' | ||
@@ -157,5 +159,9 @@ | ||
async cancelOrders(): Promise<Order[]> { | ||
return parse.orders( | ||
await this.request<RawOrder[]>('DELETE', urls.rest.account, `orders`), | ||
async cancelOrders(): Promise<OrderCancelation[]> { | ||
return parse.canceled_orders( | ||
await this.request<RawOrderCancelation[]>( | ||
'DELETE', | ||
urls.rest.account, | ||
`orders`, | ||
), | ||
) | ||
@@ -162,0 +168,0 @@ } |
@@ -544,2 +544,20 @@ /** | ||
/** | ||
* The parsed result of an order cancelation request. | ||
*/ | ||
export interface OrderCancelation { | ||
id: string | ||
status: number | ||
order: Order | ||
} | ||
/** | ||
* The id, http status code and order as part of the cancel all orders request. | ||
*/ | ||
export interface RawOrderCancelation { | ||
id: string | ||
status: number | ||
body: RawOrder | ||
} | ||
/** | ||
* The order entity with unparsed fields, exactly as Alpaca provides it. | ||
@@ -546,0 +564,0 @@ * We encourage you to use the Order interface, which has many of these fields parsed. |
@@ -15,2 +15,3 @@ export { AlpacaClient } from './client.js' | ||
Order, | ||
OrderCancelation, | ||
Position, | ||
@@ -17,0 +18,0 @@ Asset, |
@@ -24,2 +24,4 @@ import { | ||
Clock, | ||
RawOrderCancelation, | ||
OrderCancelation, | ||
} from './entities.js' | ||
@@ -116,2 +118,54 @@ | ||
function canceled_order(input: RawOrderCancelation): OrderCancelation { | ||
if (!input) { | ||
return undefined | ||
} | ||
let order = input.body | ||
// we don't want this field anymore | ||
delete input.body | ||
try { | ||
return { | ||
...input, | ||
order: { | ||
...order, | ||
raw: () => order, | ||
created_at: new Date(order.created_at), | ||
updated_at: new Date(order.updated_at), | ||
submitted_at: new Date(order.submitted_at), | ||
filled_at: new Date(order.filled_at), | ||
expired_at: new Date(order.expired_at), | ||
canceled_at: new Date(order.canceled_at), | ||
failed_at: new Date(order.failed_at), | ||
replaced_at: new Date(order.replaced_at), | ||
qty: number(order.qty), | ||
filled_qty: number(order.filled_qty), | ||
type: order.type as OrderType, | ||
side: order.side as OrderSide, | ||
time_in_force: order.time_in_force as OrderTimeInForce, | ||
limit_price: number(order.limit_price), | ||
stop_price: number(order.stop_price), | ||
filled_avg_price: number(order.filled_avg_price), | ||
status: order.status as OrderStatus, | ||
legs: orders(order.legs), | ||
trail_price: number(order.trail_price), | ||
trail_percent: number(order.trail_percent), | ||
hwm: number(order.hwm), | ||
}, | ||
} | ||
} catch (err) { | ||
throw new Error(`Order parsing failed. ${err.message}`) | ||
} | ||
} | ||
function canceled_orders( | ||
rawOrderCancelations: RawOrderCancelation[], | ||
): OrderCancelation[] { | ||
return rawOrderCancelations | ||
? rawOrderCancelations.map((value) => canceled_order(value)) | ||
: undefined | ||
} | ||
function position(rawPosition: RawPosition): Position { | ||
@@ -217,2 +271,3 @@ if (!rawPosition) { | ||
orders, | ||
canceled_orders, | ||
position, | ||
@@ -219,0 +274,0 @@ positions, |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
2292853
22698