Code Monkey home page Code Monkey logo

alpaca-trade-api-js's People

Contributors

andrewkim316 avatar andrewwoood avatar ashish-patwal avatar axelmaldonado avatar bbeale avatar bexanderthebex avatar camelpac avatar ccnlui avatar chamburr avatar dependabot[bot] avatar drew887 avatar fossilblade avatar gnvk avatar haxdds avatar kalmant avatar krisk avatar martonw avatar mdkrieg avatar motocombotag avatar neeschit avatar noramehesz avatar saket-dev01 avatar sc4recoin avatar shlomiku avatar smartchris84 avatar suddjian avatar ttt733 avatar umitanuki avatar vicary avatar wikipediabrown avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

alpaca-trade-api-js's Issues

getBars method requires specifically Date object

This is just a minor issue with the documentation. In the example provided for the getBars convenience method, the 'start' and 'end' parameters provided are strings while the method (as noted in its signature) exclusively requires Date objects .

Thanks!

Migrate to ES modules

With node 10 officially entering maintenance mode, There's no good reason for anyone being on a version of node below 10 now. Converting this to use ES modules would be forward looking, and make this module easier to consume for typescript and Node 10+ users who prefer ESM.

While the community TS project is nice, most people would loathe to diverge too far from the officially supported API interface. Switching this module to ESM would be relatively straightforward as well, and I'd be happy to throw out a PR if the community is bought into this. This would allow us to write a good index.d.ts file as well, which will provide great IDE support without a synthetic default export

[bug] TypeError: Cannot read property 'join' of undefined

@ttt733 new bug report. Running Node v10.16.0 and Alpaca 1.2.3.

/home/node/macd/node_modules/@alpacahq/alpaca-trade-api/lib/resources/polygonWebsocket.js:93
            params: topics.join(',')
                           ^

TypeError: Cannot read property 'join' of undefined
    at PolygonWebsocket.subscribe (/home/node/macd/node_modules/@alpacahq/alpaca-trade-api/lib/resources/polygonWebsocket.js:93:28)
    at PolygonWebsocket.on (/home/node/macd/node_modules/@alpacahq/alpaca-trade-api/lib/resources/polygonWebsocket.js:21:58)
    at PolygonWebsocket.emit (events.js:203:15)
    at messageArray.forEach.message (/home/node/macd/node_modules/@alpacahq/alpaca-trade-api/lib/resources/polygonWebsocket.js:50:34)
    at Array.forEach (<anonymous>)
    at PolygonWebsocket.handleMessage (/home/node/macd/node_modules/@alpacahq/alpaca-trade-api/lib/resources/polygonWebsocket.js:44:22)
    at WebSocket.conn.on (/home/node/macd/node_modules/@alpacahq/alpaca-trade-api/lib/resources/polygonWebsocket.js:25:48)
    at WebSocket.emit (events.js:198:13)
    at Receiver.receiverOnMessage (/home/node/macd/node_modules/ws/lib/websocket.js:789:20)
    at Receiver.emit (events.js:198:13)
    at Receiver.dataMessage (/home/node/macd/node_modules/ws/lib/receiver.js:422:14)
    at perMessageDeflate.decompress (/home/node/macd/node_modules/ws/lib/receiver.js:379:23)
    at _decompress (/home/node/macd/node_modules/ws/lib/permessage-deflate.js:298:9)
    at _inflate.flush (/home/node/macd/node_modules/ws/lib/permessage-deflate.js:376:7)
    at afterWrite (_stream_writable.js:485:3)
    at onwrite (_stream_writable.js:476:7)
    at InflateRaw.afterTransform (_stream_transform.js:94:3)
    at Zlib.processCallback (zlib.js:548:8)

Request: Polygon Previous Close

Please add polygon previous close to the alpaca interface as polygon data in getHistoricAggregatesV2 does not include the previous day's closing data!

Previous Close is at /v2/aggs/ticker/{ticker}/prev

Can't short on paper account

I have set this up and the API is returning an error saying account is not allowed to short. I can't find anything in the docs that reflect this. I am using a paper account. My paper account has No Shorting set to false.

[10:58:28 AM] [5/27/2020] [log] 403 - {"code":40310000,"message":"account is not allowed to short"}

backoffIncrement is not defined

@ttt733 running version 1.2.2 and seeing the following error:

ReferenceError: backoffIncrement is not defined
    at Timeout.setTimeout [as _onTimeout] (/home/node/macd/node_modules/@alpacahq/alpaca-trade-api/lib/resources/polygonWebsocket.js:115:50)
    at ontimeout (timers.js:436:11)
    at tryOnTimeout (timers.js:300:5)
    at listOnTimeout (timers.js:263:5)
    at Timer.processTimers (timers.js:223:10)
^[[90m2019-08-15T17:52:18.202Z^[[39m ^[[31m[error]^[[39m worker exited with code 1 and signal 'null'

Using .onStockTrades((subject, data)

Issue with how multiple websockets connections (and potentially sessions) are handled

I initially connected to Websockets in one project and it worked fine. I wanted to connect from another project using the same credentials, however authentication does not work.

Now I understand connections are limited to a single client, but the connection is not working from my second project even after calling client.disconnect() from my first project. Using onStateChange prints the following to the console:

State changed to authenticating
State changed to disconnected

Using the websockets example code from Polygon worked fine and resulted in a connection, which successfully authenticates, and then disconnects both the current connection and first project's connection. The good thing about this is that it prints a helpful error message to the console:
Status Update: Maximum number of connections exceeded
I can then reconnect again with no problems
Sidenote: The Polygon direct websocket connection still disconnects even when you set usePolygon to false on the Alpaca authentication object.

I believe there is an issue with how multiple connections are handled in this repo. It prevents connection from another codebase (even after the first one is disconnected), and does not provide any helpful error message

oauth updates breaking dataHttpRequest method

version 1.2.2, getting the following:

ReferenceError: oauth is not defined at Alpaca.dataHttpRequest (/Users/elleeott/projects/algo-opt/node_modules/@alpacahq/alpaca-trade-api/lib/api.js:31:14) at Alpaca.getBars (/Users/elleeott/projects/algo-opt/node_modules/@alpacahq/alpaca-trade-api/lib/resources/data/bars.js:10:15)

Sync version of each method

As a user, I really appreciate the async/await nature Node provides especially when it comes to data-driven application such as trading algo, but at the same time, it would be handy to have sync version of method to just play with APIs interactively too. As the fs package, having xxxSync() methods would be great for REPL use case.

NatsError / Authorization Violation

Hi there,
I just played around a little bit with tha Alpaca Library for node.js. When following the given example with connection via websocket, I'm getting the NatsError / Authorization Violation error just after connection established. I think that comes from the subscription to the events / symbols. In another forum I read, that this comes from using alpaca paper (test) account. My question is if this is correct and when yes, why that is the case? Because then I dont understand how to use the api with my demo (paper) account.
Furthermore it would be very much appreciated to have a little more examples based on node.js api.

Thanks!

remains is not defined

There is a Reference not defined exception at: alpaca-trade-api-js/lib/resources/websockets.js Line 172.

Change
remains = Object.keys(this.subscriptionState)
To
let remains = Object.keys(this.subscriptionState)

This fixes the exception, however the client still is subscribed to the given keys after calling the unsubscribe method. All this method seems to do is alter the subscription list but it fails to fully unsubscribe from the given keys.

ReferenceError: STATE is not defined

I just updated to version 1.2.1, and I get this error when streaming via the websocket:

C:\MySource\BinanceBot\node_modules@alpacahq\alpaca-trade-api\lib\resources\polygonWebsocket.js:122
this.emit(STATE.WAITING_TO_RECONNECT, this.session.reconnectTimeout)
^

ReferenceError: STATE is not defined
at PolygonWebsocket.reconnect (C:\MySource\BinanceBot\node_modules@alpacahq\alpaca-trade-api\lib\resources\polygonWebsocket.js:122:19)
at WebSocket.conn.once (C:\MySource\BinanceBot\node_modules@alpacahq\alpaca-trade-api\lib\resources\polygonWebsocket.js:32:22)
at Object.onceWrapper (events.js:317:30)
at emitTwo (events.js:126:13)
at WebSocket.emit (events.js:214:7)
at WebSocket.emitClose (C:\MySource\BinanceBot\node_modules@alpacahq\alpaca-trade-api\node_modules\ws\lib\websocket.js:191:10)
at Receiver.receiverOnFinish (C:\MySource\BinanceBot\node_modules@alpacahq\alpaca-trade-api\node_modules\ws\lib\websocket.js:779:20)
at emitNone (events.js:106:13)
at Receiver.emit (events.js:208:7)
at finishMaybe (_stream_writable.js:604:14)
at afterWrite (_stream_writable.js:455:3)
at onwrite (_stream_writable.js:445:7)
at Receiver.startLoop (C:\MySource\BinanceBot\node_modules@alpacahq\alpaca-trade-api\node_modules\ws\lib\receiver.js:147:5)
at perMessageDeflate.decompress (C:\MySource\BinanceBot\node_modules@alpacahq\alpaca-trade-api\node_modules\ws\lib\receiver.js:382:12)
at _decompress (C:\MySource\BinanceBot\node_modules@alpacahq\alpaca-trade-api\node_modules\ws\lib\permessage-deflate.js:298:9)
at _inflate.flush (C:\MySource\BinanceBot\node_modules@alpacahq\alpaca-trade-api\node_modules\ws\lib\permessage-deflate.js:376:7)
at afterWrite (_stream_writable.js:454:3)
at onwrite (_stream_writable.js:445:7)
at InflateRaw.afterTransform (_stream_transform.js:90:3)
at Zlib.callback (zlib.js:515:5)

Position liquidation API bug

There's a small bug/typo that was introduced in this PR: https://github.com/alpacahq/alpaca-trade-api-js/pull/23/files

This Position#closeOne() function will throw an error if you try to run it:

// position.js
function closeOne(symbol) {
  return this.httpRequest('/positions' + symbol, null, null, 'DELETE')
}


// alpaca-trade-api.js 
Alpaca.prototype.closePosition = position.closeOne

...

const alpaca = new Alpaca(...);
alpaca.closePosition('AAPL');
// Unhandled rejection StatusCodeError: 404 - {"code":40410000,"message":"endpoint not found"}

This is because closeOne is missing a /

function closeOne(symbol) {
  return this.httpRequest('/positions/' + symbol, null, null, 'DELETE')
}

authentication with auth token

hi, was wondering if it was possible to use an auth token for authentication with this package

Instead of this...

const alpaca = new Alpaca({
  keyId: <key>,
  secretKey: <secret_key>,
  paper: paperTrading,
  usePolygon: true,
});

it'd be something like this...

const alpaca = new Alpaca({
  authToken: <auth_token>,
  paper: paperTrading,
  usePolygon: true,
});

Problem with Polygon websocket reconnection

During a Polygon reconnect attempt, it appears that the variable "backoffIncrement" is not defined:

Attempting Polygon websocket reconnection...
/Users/jon/Documents/Financial/Source/testtrader2/node_modules/@alpacahq/alpaca-trade-api/lib/resources/polygonWebsocket.js:115
this.session.reconnectTimeout += backoffIncrement
^

ReferenceError: backoffIncrement is not defined
at Timeout.setTimeout [as _onTimeout] (/Users/jon/Documents/Financial/Source/testtrader2/node_modules/@alpacahq/alpaca-trade-api/lib/resources/polygonWebsocket.js:115:50)
at ontimeout (timers.js:436:11)
at tryOnTimeout (timers.js:300:5)
at listOnTimeout (timers.js:263:5)
at Timer.processTimers (timers.js:223:10)
[nodemon] app crashed - waiting for file changes before starting...

Bracket Orders: Cannot get nested order status

With an open Bracket order...

alpaca.getOrders({ status: 'open', limit: 100 })
I can see the order, but no legs...

alpaca.getOrders({ status: 'open', limit: 100, nested: true })
I get no results!

This only seems to happen with Bracket orders, not with OCO.

Is this a known issue / is there a workaround?

Subscribing to a trade stream; each key meaning

I am subscribed to a websocket trade stream for Apple T.AAPL and see the following result:

{
    "sym": "AAPL",
    "x": 4,
    "p": 169.6019,
    "s": 30,
    "c": [
        37
    ],
    "t": 1549914725299
}

What does x, s, ,c, mean in this context? Is there a mapping/documentation for these keys?

A types.d.ts file for integrated code editors.

Is it possible to include a types.d.ts file in the project? It can help people working with this API a lot, especially people using code editors that support it(like me, using VSCode). I can even help you a bit if given a reply.

Proper code samples in provided documentation.

Please include proper code samples and examples in the documentation! I am not saying that the current method is confusing(which it is, a bit), but to make it cleaner than just random documentation examples that don't apply in the actual coding process.
image

An example that could improve cleanliness could be:

AlpacaAccount.createOrder(options)

  • options : <Object> Options containing the details of the order
    • symbol : <string> Any valid Ticker symbol. (Required)
    • qty : <number> Quantity of stocks to purchase. Default: 1
    • side : <string> To buy or sell this stock, essentially which side the order is executing. Possible values:
      • "buy" Buys this stock
      • "sell" Sells this stock

Creates and executes a buy or sell order on your account.

Example:

const alpaca = await (new Alpaca({
  keyId: 'AKFZXJH121U18SHHDRFO',
  secretKey: 'pnq4YHlpMF3LhfLyOvmdfLmlz6BnASrTPQIASeiU',
  paper: true,
  usePolygon: false
})).getAccount();

alpaca.createOrder({
  symbol: "AAPL", qty: 5, side: "buy"
});

I didn't know what the other options meant so I didn't include them. xd

Start and End parameters aren't respected

const alpaca = new Alpaca({
    keyId: apiKey,
    secretKey: secret,
    paper: true,
    usePolygon: false
})

    const barset = await alpaca.getBars('1Min', ['AAPL', 'TSLA'], {start:'2020-04-20', end:'2020-04-29'});
    console.log(barset['TSLA'][0]);

This results in this response:

{
  startEpochTime: 1597426440,
  openPrice: 1651.3,
  highPrice: 1651.3,
  lowPrice: 1649.39,
  closePrice: 1649.39,
  volume: 1035
}

startEpochTime: 1597426440 is Friday, August 14, 2020 5:34:00 PM, which is definitely not between the parameters start:'2020-04-20', end:'2020-04-29'}.

Am I missing something here?

Be able to get orders by filled_at date

Hey, I would to have a discussion around a possible enhancement to getting orders.

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

it'd be awesome if we could retrieve orders by filled. If an order is filled today, I would like to be able to easily retrieve all filled orders by date.

I found out if a limit order is filled today, but created n days ago, the date filter will go based upon when the order was created, not when it was filled.

Out of Memory- Polygon Data Stream

My program uses the polygon data stream websocket interface for stock price updates. I left it running for last couple days. This morning it reported an 'Out of Memory' error. Below is the error output.

0: ExitFrame [pc: 0x1376259]
Security context: 0x223b15524791
1: join [0x223b15534be1](this=0x24d707b9a611 <JSArray[126209024]>,0x299d99886eb9 <String[#1]: ,>)
2: subscribe [0x34583e6b5139] [/work/node_modules/@alpacahq/alpaca-trade-api/lib/resources/polygonWebsocket.js:97] [bytecode=0x3ecaa5042bc1 offset=17](this=0x3a1e9e24aab9 ,0x24d707b9a611 <JSArray[126209024]>)
3: connectL...

FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory

Writing Node.js report to file: report.20200630.171239.44565.0.001.json
Node.js report completed
1: 0x9dab70 node::Abort() [/usr/local/bin/node]
2: 0x9dbd26 node::OnFatalError(char const*, char const*) [/usr/local/bin/node]
3: 0xb3b18e v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/usr/local/bin/node]
4: 0xb3b509 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/usr/local/bin/node]
5: 0xce68a5 [/usr/local/bin/node]
6: 0xff4d06 v8::internal::Runtime_FatalProcessOutOfMemoryInvalidArrayLength(int, unsigned long*, v8::internal::Isolate*) [/usr/local/bin/node]
7: 0x1376259 [/usr/local/bin/node]
Aborted
error Command failed with exit code 134.

NatsError: 'Max Connections Reached. Kicked from server due to newer API connection. This connection was the oldest

Getting intermittent errors:

{ NatsError: 'Max Connections Reached. Kicked from server due to newer API connection. This connection was the oldest.'
    at Client.processErr (node_modules/nats/lib/nats.js:1359:28)
    at Client.processInbound (node_modules/nats/lib/nats.js:1091:26)
    at Socket.stream.on (node_modules/nats/lib/nats.js:719:14)
    at Socket.emit (events.js:189:13)
    at addChunk (_stream_readable.js:284:12)
    at readableAddChunk (_stream_readable.js:265:11)
    at Socket.Readable.push (_stream_readable.js:220:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
  name: 'NatsError',
  message:
   '\'Max Connections Reached. Kicked from server due to newer API connection. This connection was the oldest.\'',
  code: 'NATS_PROTOCOL_ERR',
  chainedError: undefined }

I understand it's related to opening more than a websocket single stream, however I would expect this error to propagate through alpaca.websocket.onError(), however it does not appear to. In fact I am not sure which event listener this error is coming from.

algorithms consistently create loss, mean algorithm node.js doesn't run

Unless I'm missing something the long/short algorithm consistently produces loss of value from market open to close.
If anyone can help debug or let me know what I'm doing wrong I can screenshare or share the code I'm using.
It occurs in both the webpage example and the node.js example of the long/short algorithm.
The node.js example of the mean averaging algorithm also gets stuck on 'we have 20 bars' so I'm not sure if that algorithm would create gains or not.
If anyone can help out that'd be great!
Thanks,
Alex

Fetching using cors-api.js

Hello all!

I recently started building upon the Long Short example and am getting errors similar to the following for every request:

Access to fetch at 'https://data.alpaca.markets/v1/bars/minute?symbols=MRO&limit=10' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I found the cors-api.js file and it does exactly what I believe will solve the problem, using https://cors-anywhere.herokuapp.com as a proxy for the requests. What I can't find is any documentation or examples on how to use this. It doesn't appear to be a configurable variable when instantiating alpaca-trade-api.js, and I'm not quite an experienced enough developer to make this work on my own without a significant amount of time.

Has anyone used this or know of helpful information? There must be something since this implementation is already here!

Much gratitude,
Phillip

Cleaner API and less clutter.

Is it possible to combine any/all of these events into one event with maybe a type property as a differentiator between them? This is repeated and dirty code that I would like to console.log every time for testing and I keep having to repeat this over and over again. I would greatly appreciate any combination of similar events, as this also straightens my workflow and reduces the digging I have to do through the API.

image

I don't quite understand how it works [EXAMPLES]

Hey, developers!
I noticed a few inaccuracies in your examples.

client.onConnect(function() {
  console.log("Connected")
  client.subscribe(['alpacadatav1/T.FB', 'Q.AAPL', 'A.FB', 'AM.AAPL'])
})

client.onStockAggMin(function(subject, data) {
  console.log(`Stock agg min: ${subject}, ${data}`)
})

This does not work for PaperTrading.
But this code work

client.onConnect(function () {
    console.log("Connected")
    client.subscribe(['alpacadatav1/AM.FB'])
})

client.onStockAggMin(function (subject, data) {
    console.log(`Stock agg min: ${subject}, \n${JSON.stringify(data, null, 2)}`)
})

And onStockAggSec deprecated function? Because I don't see where A. type on this https://alpaca.markets/docs/api-documentation/api-v2/market-data/streaming/

SyntaxError: Unexpected token u in JSON for streaming

I just tried the streaming example from README and got something like this.

> 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)
... })
undefined
>
> client.connect()
> client.onStockTrades(function(subject, data) {
...   console.log(`Stock trades: ${subject}, ${data}`)
... })
undefined
> client.onStockQuotes(function(subject, data) {
...   console.log(`Stock quotes: ${subject}, ${data}`)
... })
undefined
> client.connect()
undefined
> Connected
{"bs":1,"as":3,"c":0,"t":1543951667026,"sym":"AAPL","bx":2,"ax":17,"i":137803844,"bp":177.29,"ap":177.31}
SyntaxError: Unexpected token u in JSON at position 0

Incorrect data returned by getBars function

Upon calling the getBars function with a timeframe of "1Min", and options specifying a time period of 250 Minutes (with { start: 250 minutes ago, end: now } ), it returns a seemingly random amount of bars. (In this case: 35 Bars)
There seems to be no logical explanation on this happening, and I haven't been able to determine any errors on my side.

Dedicated event documentation.

I hate the current way you do things, with .onConnect, .onDisconnect, etc. I am very sure most people would prefer a cleaner, easier to use, events API and documentation used on most other legacy APIs. You can find an example in Node.js documentation itself, with many of it's native APIs.

An example:

Event "connect"

Added in v1.4

Fired when the websocket connection is successful.

const client = new AlpacaStreamClient();
client.on("connect", () => console.log("Connection successful!")).connect();

even the examples don't work...

My code:

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

const alpaca = new Alpaca({
  keyId: 'FSKFSF2FR6MKFS6KSDIM',
  secretKey: 'KiCCx5gzVFyfskgj3fdsjkflskd3HJsar32',
  paper: true,
  usePolygon: true,                                                                                                                                                                                         
})

const client = alpaca.websocket

client.onConnect(function() {
  console.log("WS Connected")
  client.subscribe(['trade_updates', 'T.FB', 'Q.AAPL', 'A.FB', 'AM.AAPL'])
})
client.onDisconnect(() => {
  console.log("WS Disconnected")
})
client.onStateChange(newState => {
  console.log(`State changed to ${newState}`)
})

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()

When I run it:

State changed to connecting
State changed to authenticating
State changed to disconnected
WS Disconnected

And as always, no useful error message.

Dependency on 'fs' package is broken

Hi. I just installed this package. When I run it on my node server I kept getting this error:

This dependency was not found: 
* fs in ./node_modules/@alpacahq/alpaca-trade-api/node_modules/dotenv/lib/main.js, ./node_modules/request/lib/har.js

I did this:

npm install --save fs

But the error still persist because the fs package is no longer supported. See [email protected].

What am I missing?

EventEmitter memory leak detected. 11 connected listeners added. Use emitter.setMaxListeners() to increase limit FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

I am seeing my Node.js processes crash running 1.2.5 . In the logs I see:

(node:63005) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 connected listeners added. Use emitter.setMaxListeners() to increase limit
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
 1: 0x8f9d10 node::Abort() [/home/node/.nvm/versions/node/v10.16.0/bin/node]
 2: 0x8f9d5c  [/home/node/.nvm/versions/node/v10.16.0/bin/node]
 3: 0xaffd0e v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/home/node/.nvm/versions/node/v10.16.0/bin/node]
 4: 0xafff44 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/home/node/.nvm/versions/node/v10.16.0/bin/node]
 5: 0xef4152  [/home/node/.nvm/versions/node/v10.16.0/bin/node]
 6: 0xf0396f v8::internal::Heap::AllocateRawWithRetryOrFail(int, v8::internal::AllocationSpace, v8::internal::AllocationAlignment) [/home/node/.nvm/versions/node/v10.16.0/bin/node]
 7: 0xecc9c6 v8::internal::Factory::AllocateRawArray(int, v8::internal::PretenureFlag) [/home/node/.nvm/versions/node/v10.16.0/bin/node]
 8: 0xecd24a v8::internal::Factory::NewFixedArrayWithFiller(v8::internal::Heap::RootListIndex, int, v8::internal::Object*, v8::internal::PretenureFlag) [/home/node/.nvm/versions/node/v10.16.0/bin/node]
 9: 0xed9c31 v8::internal::Factory::NewJSArrayStorage(v8::internal::Handle<v8::internal::JSArray>, int, int, v8::internal::ArrayStorageAllocationMode) [/home/node/.nvm/versions/node/v10.16.0/bin/node]
10: 0xed9f2c v8::internal::Factory::NewJSArray(v8::internal::ElementsKind, int, int, v8::internal::ArrayStorageAllocationMode, v8::internal::PretenureFlag) [/home/node/.nvm/versions/node/v10.16.0/bin/node]
11: 0xe93361 v8::internal::ElementsAccessor::Concat(v8::internal::Isolate*, v8::internal::Arguments*, unsigned int, unsigned int) [/home/node/.nvm/versions/node/v10.16.0/bin/node]
12: 0xb8f349  [/home/node/.nvm/versions/node/v10.16.0/bin/node]
13: 0xb98a48 v8::internal::Builtin_ArrayConcat(int, v8::internal::Object**, v8::internal::Isolate*) [/home/node/.nvm/versions/node/v10.16.0/bin/node]
14: 0x13bd3665bf7d
Attempting Polygon websocket reconnection...
Attempting Polygon websocket reconnection...
Attempting Polygon websocket reconnection...
Attempting Polygon websocket reconnection...
Attempting Polygon websocket reconnection...
Attempting Polygon websocket reconnection...
Attempting Polygon websocket reconnection...

<--- Last few GCs --->

[63005:0x40f19a0] 41279374 ms: Mark-sweep 777.2 (814.2) -> 777.2 (783.2) MB, 202.9 / 0.0 ms  (average mu = 0.363, current mu = 0.000) last resort GC in old space requested
[63005:0x40f19a0] 41279635 ms: Mark-sweep 777.2 (783.2) -> 777.2 (782.7) MB, 261.4 / 0.0 ms  (average mu = 0.202, current mu = 0.000) last resort GC in old space requested


<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x12ed6c51e6e9 <JSObject>
    0: builtin exit frame: concat(this=0x21ccc4cf1e59 <JSArray[36616059]>,0x0806f0110c99 <JSArray[4900347]>,0x21ccc4cf1e59 <JSArray[36616059]>)

    1: subscribe [0x13e499dc9699] [/home/node/macd/node_modules/@alpacahq/alpaca-trade-api/lib/resources/polygonWebsocket.js:98] [bytecode=0x3dbedbafd539 offset=69](this=0x2074306e3dd1 <EventEmitter map = 0x2688e012aa51>,topics=0x0806f0110c99 <JSArray[4...

I am using the library with:

let client = alpaca.websocket;
client.subscribe([ 'T.FSLY',
  'T.FB',
  'T.WORK',
  'T.GOLD',
  'T.TMUS',
  'T.BRK_B',
  'T.UBNT',
  'T.NOC',
  'T.MDB',
  'T.BA',
  'T.WDAY',
  'T.F',
  'T.WFC',
  'T.OKTA',
  'T.AMZN',
  'T.ADBE',
  'T.NVDA',
  'T.NET',
  'T.ERIC',
  'T.MU',
  'T.AAPL',
  'T.NOK',
  'T.UBER',
  'T.SWKS',
  'T.MS',
  'T.BAC',
  'T.CRM',
  'T.SPY',
  'T.ESTC',
  'T.BYND',
  'T.QQQ',
  'T.TSLA',
  'T.MSFT',
  'T.NXPI',
  'T.AMD',
  'T.DATA',
  'T.KO',
  'T.RF',
  'T.LYFT',
  'T.TWLO',
  'T.DPZ',
  'T.FEYE',
  'T.PANW',
  'T.NFLX',
  'T.INTC',
  'T.LMT',
  'T.SYMC',
  'T.TEAM',
  'T.NEWR',
  'T.DDOG',
  'T.SNAP',
  'T.GS',
  'T.JPM',
  'T.RTN',
  'T.NOW',
  'T.QCOM',
  'T.SPLK' ]);

this.client.onStockTrades((subject, data) => {
    ....
});

alpaca.getCompany() returning unhandled 404 error (try-catch doesn't work)

When I run the following:

alpaca.getCompany('AMD').then(data => console.log(data));

It works on most assets, but on some (for example 'KRTX') I get the following error:

Unhandled rejection StatusCodeError: 404 - {"error":"Not Found"}
    at new StatusCodeError (C:\Users\imman\OneDrive\Websites\Stocks2\node_modules\request-promise-core\lib\errors.js:32:15)     
    at Request.plumbing.callback (C:\Users\imman\OneDrive\Websites\Stocks2\node_modules\request-promise-core\lib\plumbing.js:104:33)
    at Request.RP$callback [as _callback] (C:\Users\imman\OneDrive\Websites\Stocks2\node_modules\request-promise-core\lib\plumbing.js:46:31)
    at Request.self.callback (C:\Users\imman\OneDrive\Websites\Stocks2\node_modules\request\request.js:185:22)
    at Request.emit (events.js:315:20)
    at Request.<anonymous> (C:\Users\imman\OneDrive\Websites\Stocks2\node_modules\request\request.js:1154:10)
    at Request.emit (events.js:315:20)
    at IncomingMessage.<anonymous> (C:\Users\imman\OneDrive\Websites\Stocks2\node_modules\request\request.js:1076:12)
    at Object.onceWrapper (events.js:421:28)
    at IncomingMessage.emit (events.js:327:22)
    at endReadableNT (_stream_readable.js:1220:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)

Wrapping the .getCompany() code in a try-catch does not to catch the exception:

try {
    alpaca.getCompany('AMD').then(data => console.log(data));
} catch (err) {
    console.log(err);
}

How can I catch the exception?

Handle rate limiting

Right now if you hit the api rate limit, the library won't do anything to help you. We should change that.

Update to support Alpaca V2 please

Update to support Alpaca V2 please. This should be easy, as I see you've done it for your python library. tried doing it by adjusting the base URL, but seems to throw an error.

Bracket Order: Cannot get order status after entry is filled.

Before a bracket entry is filled, everything seems to work fine. I can see the order with the following code:
getOrders({ status: 'open', limit: 100, nested: true })

However, once the bracket entry order is filled there seems to be two issues:

First issue:
nested: true does not return any results at all, even though I still have two open orders (take_profit and stop_loss). I understand they are no longer nested, but I'd assume they should still be returned otherwise it looks like I have no open orders at all.

Second issue:
nested: false, lets me see the take_profit order, but I cannot see the stop_loss order whether I use nested: true or not.

AggSec Websocket Listener Question

In the websocket_listener example, I see a function

data_client.onStockAggSec(function (subject, data) {
     console.log(`Stock agg sec: ${subject}, ${data}`)
})

I was wondering what I would need to do to subscribe to that. I tried alpacadatav1/AS.AAPL without luck.

  client.subscribe([
    "alpacadatav1/Q.AAPL",
    "alpacadatav1/AS.AAPL",
    "alpacadatav1/AM.AAPL",
  ]);

How to subscribe to websocket onStockTrades and onStockQuotes

I am not fully understanding how to use:

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.*'.

Do these require a 3rd party account at Polygon? Can we get some more detailed examples?

TypeScript Definition File

I really enjoy using this package, but wish it had a types package so I could make better use of the API and get compile-time checking. I'd be happy to create a Definition file, but I haven't had any luck so far. If someone is able to get me started, I'd be happy to complete as much of it as possible.

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.