Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@master-chief/alpaca

Package Overview
Dependencies
Maintainers
1
Versions
86
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@master-chief/alpaca - npm Package Compare versions

Comparing version 1.0.7 to 1.0.8

.github/workflows/prettify.yml

21

dist/index.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var client_1 = require("./lib/client");
Object.defineProperty(exports, "Client", {
enumerable: true,
get: function () {
return client_1.Client;
},
});
Object.defineProperty(exports, "Client", { enumerable: true, get: function () { return client_1.Client; } });
var stream_1 = require("./lib/stream");
Object.defineProperty(exports, "Stream", {
enumerable: true,
get: function () {
return stream_1.Stream;
},
});
Object.defineProperty(exports, "Stream", { enumerable: true, get: function () { return stream_1.Stream; } });
var url_1 = require("./lib/url");
Object.defineProperty(exports, "URL", {
enumerable: true,
get: function () {
return url_1.URL;
},
});
Object.defineProperty(exports, "URL", { enumerable: true, get: function () { return url_1.URL; } });
"use strict";
var __importDefault =
(this && this.__importDefault) ||
function (mod) {
return mod && mod.__esModule ? mod : { default: mod };
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -15,271 +13,140 @@ exports.Client = void 0;

class Client {
constructor(params) {
this.params = params;
this.limiter = new limiter_1.RateLimiter(199, "minute");
}
async isAuthenticated() {
try {
await this.getAccount();
return true;
} catch {
return false;
constructor(params) {
this.params = params;
this.limiter = new limiter_1.RateLimiter(199, 'minute');
}
}
getAccount() {
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_ACCOUNT,
"account"
);
}
getOrder(params) {
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_ACCOUNT,
`orders/${
params.order_id || params.client_order_id
}?${qs_1.default.stringify({
nested: params.nested,
})}`
);
}
getOrders(params) {
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_ACCOUNT,
`orders?${qs_1.default.stringify(params)}`
);
}
placeOrder(params) {
return this.request(
http_method_enum_1.default.POST,
url_1.URL.REST_ACCOUNT,
`orders`,
params
);
}
replaceOrder(params) {
return this.request(
http_method_enum_1.default.PATCH,
url_1.URL.REST_ACCOUNT,
`orders/${params.order_id}`,
params
);
}
cancelOrder(params) {
return this.request(
http_method_enum_1.default.DELETE,
url_1.URL.REST_ACCOUNT,
`orders/${params.order_id}`
);
}
cancelOrders() {
return this.request(
http_method_enum_1.default.DELETE,
url_1.URL.REST_ACCOUNT,
`orders`
);
}
getPosition(params) {
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_ACCOUNT,
`positions/${params.symbol}`
);
}
getPositions() {
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_ACCOUNT,
`positions`
);
}
closePosition(params) {
return this.request(
http_method_enum_1.default.DELETE,
url_1.URL.REST_ACCOUNT,
`positions/${params.symbol}`
);
}
closePositions() {
return this.request(
http_method_enum_1.default.DELETE,
url_1.URL.REST_ACCOUNT,
`positions`
);
}
getAsset(params) {
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_ACCOUNT,
`assets/${params.asset_id_or_symbol}`
);
}
getAssets(params) {
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_ACCOUNT,
`assets?${qs_1.default.stringify(params)}`
);
}
getWatchlist(params) {
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_ACCOUNT,
`watchlists/${params.uuid}`
);
}
getWatchlists() {
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_ACCOUNT,
`watchlists`
);
}
createWatchlist(params) {
return this.request(
http_method_enum_1.default.POST,
url_1.URL.REST_ACCOUNT,
`watchlists`,
params
);
}
updateWatchlist(params) {
return this.request(
http_method_enum_1.default.PUT,
url_1.URL.REST_ACCOUNT,
`watchlists/${params.uuid}`,
params
);
}
addToWatchlist(params) {
return this.request(
http_method_enum_1.default.POST,
url_1.URL.REST_ACCOUNT,
`watchlists/${params.uuid}`,
params
);
}
removeFromWatchlist(params) {
return this.request(
http_method_enum_1.default.DELETE,
url_1.URL.REST_ACCOUNT,
`watchlists/${params.uuid}/${params.symbol}`
);
}
deleteWatchlist(params) {
return this.request(
http_method_enum_1.default.DELETE,
url_1.URL.REST_ACCOUNT,
`watchlists/${params.uuid}`
);
}
getCalendar(params) {
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_ACCOUNT,
`calendar?${qs_1.default.stringify(params)}`
);
}
getClock() {
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_ACCOUNT,
`clock`
);
}
getAccountConfigurations() {
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_ACCOUNT,
`account/configurations`
);
}
updateAccountConfigurations(params) {
return this.request(
http_method_enum_1.default.PATCH,
url_1.URL.REST_ACCOUNT,
`account/configurations`,
params
);
}
getAccountActivities(params) {
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_ACCOUNT,
`account/activities/${params.activity_type}?${qs_1.default.stringify(
params
)}`
);
}
getPortfolioHistory(params) {
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_ACCOUNT,
`account/portfolio/history?${qs_1.default.stringify(params)}`
);
}
getBars(params) {
var transformed = {};
// join the symbols into a comma-delimited string
transformed = params;
transformed["symbols"] = params.symbols.join(",");
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_MARKET_DATA,
`bars/${params.timeframe}?${qs_1.default.stringify(params)}`
);
}
getLastTrade(params) {
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_MARKET_DATA,
`last/stocks/${params.symbol}`
);
}
getLastQuote(params) {
return this.request(
http_method_enum_1.default.GET,
url_1.URL.REST_MARKET_DATA,
`last_quote/stocks/${params.symbol}`
);
}
request(method, url, endpoint, data) {
// modify the base url if paper is true
if (this.params.paper && url == url_1.URL.REST_ACCOUNT) {
url = url_1.URL.REST_ACCOUNT.replace("api.", "paper-api.");
async isAuthenticated() {
try {
await this.getAccount();
return true;
}
catch {
return false;
}
}
// convert any dates to ISO 8601 for Alpaca
if (data) {
for (let [key, value] of Object.entries(data)) {
if (value instanceof Date) {
data[key] = value.toISOString();
getAccount() {
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_ACCOUNT, 'account');
}
getOrder(params) {
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_ACCOUNT, `orders/${params.order_id || params.client_order_id}?${qs_1.default.stringify({
nested: params.nested,
})}`);
}
getOrders(params) {
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_ACCOUNT, `orders?${qs_1.default.stringify(params)}`);
}
placeOrder(params) {
return this.request(http_method_enum_1.default.POST, url_1.URL.REST_ACCOUNT, `orders`, params);
}
replaceOrder(params) {
return this.request(http_method_enum_1.default.PATCH, url_1.URL.REST_ACCOUNT, `orders/${params.order_id}`, params);
}
cancelOrder(params) {
return this.request(http_method_enum_1.default.DELETE, url_1.URL.REST_ACCOUNT, `orders/${params.order_id}`);
}
cancelOrders() {
return this.request(http_method_enum_1.default.DELETE, url_1.URL.REST_ACCOUNT, `orders`);
}
getPosition(params) {
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_ACCOUNT, `positions/${params.symbol}`);
}
getPositions() {
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_ACCOUNT, `positions`);
}
closePosition(params) {
return this.request(http_method_enum_1.default.DELETE, url_1.URL.REST_ACCOUNT, `positions/${params.symbol}`);
}
closePositions() {
return this.request(http_method_enum_1.default.DELETE, url_1.URL.REST_ACCOUNT, `positions`);
}
getAsset(params) {
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_ACCOUNT, `assets/${params.asset_id_or_symbol}`);
}
getAssets(params) {
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_ACCOUNT, `assets?${qs_1.default.stringify(params)}`);
}
getWatchlist(params) {
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_ACCOUNT, `watchlists/${params.uuid}`);
}
getWatchlists() {
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_ACCOUNT, `watchlists`);
}
createWatchlist(params) {
return this.request(http_method_enum_1.default.POST, url_1.URL.REST_ACCOUNT, `watchlists`, params);
}
updateWatchlist(params) {
return this.request(http_method_enum_1.default.PUT, url_1.URL.REST_ACCOUNT, `watchlists/${params.uuid}`, params);
}
addToWatchlist(params) {
return this.request(http_method_enum_1.default.POST, url_1.URL.REST_ACCOUNT, `watchlists/${params.uuid}`, params);
}
removeFromWatchlist(params) {
return this.request(http_method_enum_1.default.DELETE, url_1.URL.REST_ACCOUNT, `watchlists/${params.uuid}/${params.symbol}`);
}
deleteWatchlist(params) {
return this.request(http_method_enum_1.default.DELETE, url_1.URL.REST_ACCOUNT, `watchlists/${params.uuid}`);
}
getCalendar(params) {
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_ACCOUNT, `calendar?${qs_1.default.stringify(params)}`);
}
getClock() {
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_ACCOUNT, `clock`);
}
getAccountConfigurations() {
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_ACCOUNT, `account/configurations`);
}
updateAccountConfigurations(params) {
return this.request(http_method_enum_1.default.PATCH, url_1.URL.REST_ACCOUNT, `account/configurations`, params);
}
getAccountActivities(params) {
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_ACCOUNT, `account/activities/${params.activity_type}?${qs_1.default.stringify(params)}`);
}
getPortfolioHistory(params) {
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_ACCOUNT, `account/portfolio/history?${qs_1.default.stringify(params)}`);
}
getBars(params) {
var transformed = {};
// join the symbols into a comma-delimited string
transformed = params;
transformed['symbols'] = params.symbols.join(',');
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_MARKET_DATA, `bars/${params.timeframe}?${qs_1.default.stringify(params)}`);
}
getLastTrade(params) {
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_MARKET_DATA, `last/stocks/${params.symbol}`);
}
getLastQuote(params) {
return this.request(http_method_enum_1.default.GET, url_1.URL.REST_MARKET_DATA, `last_quote/stocks/${params.symbol}`);
}
request(method, url, endpoint, data) {
// modify the base url if paper is true
if (this.params.paper && url == url_1.URL.REST_ACCOUNT) {
url = url_1.URL.REST_ACCOUNT.replace('api.', 'paper-api.');
}
}
// convert any dates to ISO 8601 for Alpaca
if (data) {
for (let [key, value] of Object.entries(data)) {
if (value instanceof Date) {
data[key] = value.toISOString();
}
}
}
return new Promise(async (resolve, reject) => {
// do rate limiting
if (this.params.rate_limit) {
await new Promise((resolve) => this.limiter.removeTokens(1, resolve));
}
await node_fetch_1.default(`${url}/${endpoint}`, {
method: method,
headers: {
'APCA-API-KEY-ID': this.params.credentials.key,
'APCA-API-SECRET-KEY': this.params.credentials.secret,
},
body: JSON.stringify(data),
})
.then(async (response) => (await response.json().catch(() => false)) || {})
.then((json) => 'code' in json && 'message' in json ? reject(json) : resolve(json))
.catch(reject);
});
}
return new Promise(async (resolve, reject) => {
// do rate limiting
if (this.params.rate_limit) {
await new Promise((resolve) => this.limiter.removeTokens(1, resolve));
}
await node_fetch_1
.default(`${url}/${endpoint}`, {
method: method,
headers: {
"APCA-API-KEY-ID": this.params.credentials.key,
"APCA-API-SECRET-KEY": this.params.credentials.secret,
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((response) =>
// is it an alpaca error response?
"code" in response && "message" in response
? reject(response)
: resolve(response)
)
.catch(reject);
});
}
}
exports.Client = Client;
"use strict";
var __importDefault =
(this && this.__importDefault) ||
function (mod) {
return mod && mod.__esModule ? mod : { default: mod };
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -12,122 +10,111 @@ exports.Stream = void 0;

class Stream extends events_1.EventEmitter {
constructor(params) {
// Makes a new event emitter :D
super();
this.params = params;
this.subscriptions = [];
this.authenticated = false;
// if we haven't made a connection, create one now
this.connection = new ws_1.default(params.host)
// Emits when the websocket is open
.once("open", () => {
// Sends an authentication request if you aren't authorized yet
if (!this.authenticated)
this.connection.send(
JSON.stringify({
action: "authenticate",
data: {
key_id: params.credentials.key,
secret_key: params.credentials.secret,
},
})
);
// Emits the open event
this.emit("open", this);
})
// Emit a close event on websocket close.
.once("close", () => this.emit("close", this))
// listen to incoming messages
.on("message", (message) => {
// Parses the object
const object = JSON.parse(message.toString());
// if the state is pending auth and this is an auth message, change the state
// < {"stream":"authorization","data":{"action":"authenticate","status":"authorized"}}
if ("stream" in object && object.stream == "authorization")
if (object.data.status == "authorized")
// all good :D
(this.authenticated = true),
this.emit("authenticated", this),
console.log("Connected to the websocket.");
else {
// Closes the connection
this.connection.close();
// Then throws an error
throw new Error(
"There was an error in authorizing your websocket connection. Object received: " +
JSON.stringify(object, null, 2)
);
}
// callback regardless of whether or not we acted on the message above
this.emit("message", object);
// call any of the convenience methods that apply to this message
if ("stream" in object)
this.emit(
{
trade_updates: "trade_updates",
account_updates: "account_updates",
T: "trade",
Q: "quote",
AM: "aggregate_minute",
}[object.stream.split(".")[0]],
object.data
);
})
// Emits an error event.
.on("error", (err) => this.emit("error", err));
}
/**
* Sends a message to the connected websocket.
* @param message The message itself
*/
send(message) {
// You need to be authenticated to send further messages
if (!this.authenticated) {
throw new Error("You can't send a message until you are authenticated!");
constructor(params) {
// Makes a new event emitter :D
super();
this.params = params;
this.subscriptions = [];
this.authenticated = false;
// if we haven't made a connection, create one now
this.connection = new ws_1.default(params.host)
// Emits when the websocket is open
.once('open', () => {
// Sends an authentication request if you aren't authorized yet
if (!this.authenticated)
this.connection.send(JSON.stringify({
action: 'authenticate',
data: {
key_id: params.credentials.key,
secret_key: params.credentials.secret,
},
}));
// Emits the open event
this.emit('open', this);
})
// Emit a close event on websocket close.
.once('close', () => this.emit('close', this))
// listen to incoming messages
.on('message', (message) => {
// Parses the object
const object = JSON.parse(message.toString());
// if the state is pending auth and this is an auth message, change the state
// < {"stream":"authorization","data":{"action":"authenticate","status":"authorized"}}
if ('stream' in object && object.stream == 'authorization')
if (object.data.status == 'authorized')
// all good :D
(this.authenticated = true),
this.emit('authenticated', this),
console.log('Connected to the websocket.');
else {
// Closes the connection
this.connection.close();
// Then throws an error
throw new Error('There was an error in authorizing your websocket connection. Object received: ' +
JSON.stringify(object, null, 2));
}
// callback regardless of whether or not we acted on the message above
this.emit('message', object);
// call any of the convenience methods that apply to this message
if ('stream' in object)
this.emit({
trade_updates: 'trade_updates',
account_updates: 'account_updates',
T: 'trade',
Q: 'quote',
AM: 'aggregate_minute',
}[object.stream.split('.')[0]], object.data);
})
// Emits an error event.
.on('error', (err) => this.emit('error', err));
}
// convert object to json
if (typeof message == "object") {
message = JSON.stringify(message);
/**
* Sends a message to the connected websocket.
* @param message The message itself
*/
send(message) {
// You need to be authenticated to send further messages
if (!this.authenticated) {
throw new Error("You can't send a message until you are authenticated!");
}
// convert object to json
if (typeof message == 'object') {
message = JSON.stringify(message);
}
// Sends the message.
this.connection.send(message);
// Returns instance, making this chainable
return this;
}
// Sends the message.
this.connection.send(message);
// Returns instance, making this chainable
return this;
}
/**
* Subscribes to channels
* @param channels The channels you want to subscribe to
*/
subscribe(channels) {
// Adds a subscription
this.subscriptions.push(...channels);
// Sends a message specifying to subscribe.
return this.send(
JSON.stringify({
action: "listen",
data: {
streams: channels,
},
})
);
}
/**
* Unsubscribes from given channels
* @param channels The channels you want to unsubscribe from
*/
unsubscribe(channels) {
// Removes these channels
for (let i = 0, ln = this.subscriptions.length; i < ln; i++)
if (channels.includes(this.subscriptions[i]))
this.subscriptions.splice(i, 1);
// Send the removal to the websocket
return this.send(
JSON.stringify({
action: "unlisten",
data: {
streams: channels,
},
})
);
}
/**
* Subscribes to channels
* @param channels The channels you want to subscribe to
*/
subscribe(channels) {
// Adds a subscription
this.subscriptions.push(...channels);
// Sends a message specifying to subscribe.
return this.send(JSON.stringify({
action: 'listen',
data: {
streams: channels,
},
}));
}
/**
* Unsubscribes from given channels
* @param channels The channels you want to unsubscribe from
*/
unsubscribe(channels) {
// Removes these channels
for (let i = 0, ln = this.subscriptions.length; i < ln; i++)
if (channels.includes(this.subscriptions[i]))
this.subscriptions.splice(i, 1);
// Send the removal to the websocket
return this.send(JSON.stringify({
action: 'unlisten',
data: {
streams: channels,
},
}));
}
}
exports.Stream = Stream;

@@ -6,6 +6,6 @@ "use strict";

(function (URL) {
URL["REST_ACCOUNT"] = "https://api.alpaca.markets/v2";
URL["REST_MARKET_DATA"] = "https://data.alpaca.markets/v1";
URL["WSS_ACCOUNT"] = "wss://api.alpaca.markets/stream";
URL["WSS_MARKET_DATA"] = "wss://data.alpaca.markets/stream";
})((URL = exports.URL || (exports.URL = {})));
URL["REST_ACCOUNT"] = "https://api.alpaca.markets/v2";
URL["REST_MARKET_DATA"] = "https://data.alpaca.markets/v1";
URL["WSS_ACCOUNT"] = "wss://api.alpaca.markets/stream";
URL["WSS_MARKET_DATA"] = "wss://data.alpaca.markets/stream";
})(URL = exports.URL || (exports.URL = {}));

@@ -286,9 +286,8 @@ import fetch from 'node-fetch'

})
.then((response) => response.json())
.then((response) =>
// is it an alpaca error response?
'code' in response && 'message' in response
? reject(response)
: resolve(response)
.then(
async (response) => (await response.json().catch(() => false)) || {}
)
.then((json) =>
'code' in json && 'message' in json ? reject(json) : resolve(json)
)
.catch(reject)

@@ -295,0 +294,0 @@ })

{
"name": "@master-chief/alpaca",
"version": "1.0.7",
"version": "1.0.8",
"description": "A TypeScript Node.js library for the https://alpaca.markets REST API and WebSocket streams.",

@@ -5,0 +5,0 @@ "main": "dist/index.js",

@@ -8,4 +8,3 @@ # alpaca

A TypeScript Node.js library for the <https://alpaca.markets> REST API and
WebSocket streams.
a TypeScript Node.js library for the https://alpaca.markets REST API and WebSocket streams

@@ -12,0 +11,0 @@ ## Contents

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc