Giter VIP home page Giter VIP logo

client-js's People

Contributors

akash9l avatar bassochette avatar codingmatty avatar ctrahey avatar dependabot[bot] avatar dylanmoz avatar hsynlms avatar hunterl avatar ianrios avatar jaydenwindle avatar joedursun avatar jogenshah avatar justinpolygon avatar khuzha avatar mpatel18 avatar narciero avatar nikofarrelly avatar randomf avatar ruckonic avatar stormy110 avatar teambailey avatar tenorok avatar tharnach avatar timetraveler328 avatar travisgroth avatar williamconnatser avatar yehudabortz 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

client-js's Issues

Convenient keys

Hey, great library so far!

The only thing I can see would be making the keys of objects more human friendly. There isn't an exact mapping we are looking for, just whatever the actual key means -> camel cased name.

eg:

let trade = {
    ticker: rawTrade.T,
    timestamp: rawTrade.t,
    size: rawTrade.s,
    price: rawTrade.p,
    // etc etc
}

I think this will make the library much easier for users to consume.

Thanks,

Invalid query string when using object parameters in IPolygonQuery

When object parameter is used in IPolygonQuery the API request fails. For instance for

    const query: IPolygonQuery = {
      timestamp: {
        lte: '2022-05-12',
      },
      order: "desc",
      limit: 5,
    };

as a query parameter of polygonClient.stocks.trades(), following string is produced by query-string's stringify function: limit=5&order=desc&timestamp=%5Bobject%20Object%5D. Encoding objects is not supported by stringify.

See https://github.com/polygon-io/client-js/blob/master/src/rest/transport/request.ts

Add React Native support

This library currently only supports Node.js, due to it's use of https, ws and querystring.

Similarly to #8, it would be awesome to be able to use this library in a React Native environment as well.

v2HistoricTrades Fails

https://github.com/polygon-io/client-js/blob/master/src/rest/stocks/v2HistoricTrades.ts#L80

As described in the docs

export const formatIV2HistoricTradeResultRaw = (
  raw: IV2HistoricTradesResultRaw
): IV2HistoricTradesResultFormatted => ({
  ...raw,
  ticks: raw.ticks.map(formatITradeV2Raw)
});

Should be

export const formatIV2HistoricTradeResultRaw = (
  raw: IV2HistoricTradesResultRaw
): IV2HistoricTradesResultFormatted => ({
  ...raw,
  ticks: raw.results.map(formatITradeV2Raw)
});

API key is logged on failed responses

As the API key is put into the URL by this library instead of authroisation header - when the network fails, the URL is logged.

This is a security issue and should be patched

The package @polygon.io/client-js is empty

I tried to install using npm install @polygon.io/client-js.
If I look at the package-lock.json, it brings me to this https://registry.npmjs.org/@polygon.io/client-js/-/client-js-5.0.2.tgz, but turns out it is an empty package.

Any idea?

1 minute websocket connection is inconsistent

Hello,

I don't know whether this is on my end or yours, probably my end. I'm trying to get every stock's 1 minute bar data, started testing with AAPL but even though there are bars, polygon.io sometimes doesn't send them to me, completely skipping them.

For instance, I created a connection at 16:34 today.

At 16:41, I checked and it turns out it skipped 16:36 and 16:40 bars. My internet connection speed is 50mbps, I can download ~5 megabytes per second.

What could be the problem here?

Here's my code.

import { websocketClient } from '@polygon.io/client-js'

const stocksWS = websocketClient('myapikeyishere').stocks()

export async function sleep (ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

export async function polygon () {
  await sleep(1000)
  console.log('Started processing data...')
  await stocksWS.send('{"action":"subscribe", "params":"AM.*"}')

  stocksWS.onmessage = async ({ data }) => {
    const [message] = JSON.parse(data)

    if (message.ev === 'AM') {
      const ticker = message.sym

      if (ticker === 'AAPL') {
        console.log(ticker + ' ' + message.s + ' ' + message.ev)
      }
    }
}

polygon()

Issue getting the Module to import

When using the import {restClient} from "@polygon.io/client-js"; I am getting an error that

image

I can see in the source tab of the inspect that it is grabbing the main.js file as shown here which should be the correct file to get the rest or websocket libraries

image

the file is formatted as a commonjs file and not an ES Module. What am I missing to get the api module to work?
thanks

Last Quote for a Symbol v2

Hi,

When will the Last Quote for a Symbol v2 API be supported natively in the client library?

Thanks.

Forex aggregatesGroupedDaily endpoint url seems incorrect

The url here doesn't match the current documentation. Instead of forex it should contain fx as documented here.

I noticed this because calling the documented fx url works, but using the polygon js client returns an empty list for the same endpoint. It seems likely that the issue is caused by this mismatched url.

Expanded Documentation

Hi All,

I'm really loving Polygon and am super stoked to implement it into some apps. The documentation on using the API is top notch and beautifully done. However, I notice some of the client libraries, there are minimal code examples and takes a little bit to correlate how to use the library with the documentation available.

With that being said, I'd love to work on writing some docs to help you out. I'll be heavily implementing the PHP and JS libraries and can work on documenting them and providing code examples if this is something you are interested in.

Approach

I'd write everything in markdown so you can use it in the Github Wiki, or throw it into the documentation engine of your choice.

Would this be helpful?

News endpoint doesn't include access-control headers

the new 'news' endpoint doesn't return access-control headers, causing CORS issue when requesting via ajax in the browser. Most (if not all) other endpoints do include the headers. Here's an example response:
news

Version 2.1.2 is not backward compatible with v2.0.2

Semantic versioning says that a change to the minor release number should be fully backward compatible with the previous version. But code written for v2.0.x will not run with v2.1.x

e.g.

const {websocketClient} = require('polygon.io')

const ws = websocketClient(node.apiKey).stocks()

ws.on('open', () => {
  send(`{"action":"subscribe","params":"IBM"}`)
})

This works fine at v2.0.2 but fails at v2.1.2 complaining that ws is not a event handler

TypeError: ws.on is not a function

Consumer facing type definitions?

Hey!

I noticed the whole source code is pretty much typed correctly via typescript, but the built library does not export these typings.

Is there a reason for this? It should be fairly trivial to expose them... would make UX of using the library much better.

I can submit a PR if no concerns

Incorrect interface for ISession

Using v6.1.3.

I was attempting to read summary data on the Launchpad API. I noticed the session interface has a typo.

export interface ISession {
    ...
    pervious_close: number;
    ...
}

Based on the data I see that should be previous_close: number;

Incorrect stock financials field names

Getting multiple responses for conditions Polygon IO API

Hi Team , We are trying to consume conditions polygon IO API and we are passing the expected parameters (see attached), but the request url / response parameters seems to be very different
image

https://api.polygon.io/v3/reference/conditions?0=x&1=B&10=T&11=T&12=5&13=4&14=h&15=j&16=m&17=n&18=D&19=S&2=4&20=t&21=n&22=v&23=n&24=n&25=K&26=U&27=D&28=_&29=a&3=j&30=p&31=H&4=Q&5=V&6=m&7=4&8=3&9=h&apiKey=xxxxxxxxxxxxxxxx

image

Please see the expected output in the below mentioned url
https://polygon.io/docs/stocks/get_v3_reference_conditions

Please find the output getting in the attached screenshot ( we are consuming the same API which was provided in the above url but the response is different)

image

Please do the needful

Getting multiple responses for Ticker Polgon IO

Hi Team , We are trying to consume ticker polygon IO API and we are passing the expected parameters (see attached), but the request url / response parameters seems to be very different

Please see the expected output in the below mentioned url
https://polygon.io/docs/stocks/get_v3_reference_tickers

Please find the output getting in the attached screenshot ( we are consuming the same API which was provided in the above url but the response is different)

Please do the needful

image

PolygonIOTicker

Bug/typo in return type of results in lastQuote.ts

File : client-js/src/rest/stocks/lastQuote.ts

The return type of property "results" of the Interface "ILastQuote" should not be an array according to the documentation.

export interface ILastQuote {
  request_id?: string;
  status?: string;
  results?: ITradeInfo[]; // => results?: ITradeInfo ;
}

Add Typescript types for all clients and export all types from package

This package is currently difficult to use in a Typescript app, since none of the clients have type declarations and many of the API response types aren't exposed.

It would be awesome if this package exported all client and response types to make it easier to use in Typescript apps.

Error handling

Please provide better error handling.

I made a simple mistake, I put a date as '2020-1-1' instead of '2020-01-01'.

But the error I receive is

(node:30158) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'map' of undefined
    at Object.exports.formatIAggResponseRaw (/Users/jbales/Personal-Repos/market-mind-js/node_modules/polygon.io/lib/rest/stocks/aggregates.js:14:104)
    at /Users/jbales/Personal-Repos/market-mind-js/node_modules/polygon.io/lib/rest/stocks/aggregates.js:21:20
    at Generator.next (<anonymous>)
    at fulfilled (/Users/jbales/Personal-Repos/market-mind-js/node_modules/polygon.io/lib/rest/stocks/aggregates.js:5:58)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:30158) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:30158) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

This is hardly helpful.

I had to go to the source code and change it to this

exports.formatIAggResponseRaw = (raw) => {
    console.log('raw', raw);
    return (Object.assign(Object.assign({}, raw), { results: raw.results.map(formatIAggv2Raw) }))
};

Only then I could see that the error was

raw {
  status: 'ERROR',
  request_id: '6e801099337ce7a767a9e03041aca080',
  error: "Could not parse the time parameter: 'from'. Use YYYY-MM-DD or Unix MS Timestamps"
}

We shouldn't have to dig into source code to discover errors, large or small.

Please incorporate error handling propagation in all your calls so error messages are clear and helpful.

Internal error is surfaced when no data is available

[Nest] 3177   - 05/15/2021, 10:28:47 AM   Cannot read property 'map' of undefined +43ms
TypeError: Cannot read property 'map' of undefined
    at Object.formatIAggResponseRaw (/Users/justingriffith/Workspaces/trading-algorithms/node_modules/polygon.io/lib/rest/stocks/aggregates.js:15:102)
    at /Users/justingriffith/Workspaces/trading-algorithms/node_modules/polygon.io/lib/rest/crypto/aggregates.js:22:25
    at Generator.next (<anonymous>)
    at fulfilled (/Users/justingriffith/Workspaces/trading-algorithms/node_modules/polygon.io/lib/rest/crypto/aggregates.js:5:58)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

When using your client I would expect to either receive a different error or merely get back an empty result set. This kind of thing should be handled internally within your library in practice.

Unhandled promise rejection when connection refused

Version: 6.2.0

I see an unhandled promise rejection when there is a connection refused error. This error isn't reaching my code that is making the call.

    const polygonSummaries = await this.polygonClient.stocks.summaries(
      {
        'ticker.any_of': tickerSymbols.join(','),
      },
      edgeHeaders,
    );

I see this error in the logs when we run up against a rate limit. I was testing to see what the capacity might be like. That is fine but I need to be able to handle the error properly and it gets lost to the global error handler because it's an unhandled promise rejection. We are running Datadog tracing so that's why you see it in the error handling stack.

FetchError: request to https://api.polygon.io/v1/summaries?apiKey=***REDACTED***&ticker.any_of=AAPL%2CAMZN%2CGOOG%2CMETA%2CTSLA failed, reason: connect ECONNREFUSED 198.44.194.22:443
    at ClientRequest.<anonymous> (/backend/node_modules/node-fetch/lib/index.js:1491:11)
    at ClientRequest.emit (node:events:513:28)
    at ClientRequest.req.emit (/backend/node_modules/dd-trace/packages/datadog-instrumentations/src/http/client.js:95:23)
    at TLSSocket.socketErrorListener (node:_http_client:494:9)
    at TLSSocket.emit (node:events:525:35)
    at TLSSocket.emit (/backend/node_modules/dd-trace/packages/datadog-instrumentations/src/net.js:61:25)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

Add browser support

This library currently only supports Node.js, due to it's use of https, ws and querystring.

It would be awesome if this library could be used in a browser environment as well.

Reference Tickers V3

Hi,

When will v3/reference/tickers be supported in the client library?

Thanks.

Symbol field is not case insensitive

In the api explorer, the symbol field does not work unless all letters are capitalized. Options to fix:

Change the backend to uppercase the letters.
Change the clients to uppercase the letters.
Provide an error that mentions the letters being lowercased as an issue.

Export elements defined in transport/request to facilitate mocking.

I want to be able to do the same kind of mock that's used in src/rest/reference/index.test.ts, but I can't because I can't do the equivalent of

import * as request from "../transport/request";

because the elements of transport/request aren't exported from the package.

Ticker API - Response Data

Ticker API response, as in the library is form like: (Array of ITickers)
image

But the actual result is form like: (Object with other fields, the results field is the array of ITickers)
image

It makes use write workarounds.

Timeout?

I can not find a way to set a timeout on the API client, is there a way to do so?

Recently Polygon.io services went down and the timeout looks to be 1 and a half minute.

Is there a way we can reduce this timeout?

Aggregates API throws error when there are no results

When making a call to the aggregates API that would result in a resultCount of 0, the API does not return a results field which causes this line to throw an error whenever you make such a request via client.stocks.aggregates().

There should be a check here that the results object exists, and the type for IAggResponseRaw should have results be optional.

How is the reconnect handled?

According to the source code, it looks like reconnect mechanism isn't there. Is this the case? I think there should be a reconnect functionality for this client to be really useful.

Errors sometimes come as JSON strings in a message

Version: 6.2.1

I'm starting to use some reference endpoints. The tickerDetails() throws an error if the specified ticker is not found. That's fine, but the content of the error leaves something to be desired. The machine-readable status is buried in the message as a JSON string.

This is how I'm handling it now...

    try {
      const result = await this.client.reference.tickerDetails(
        symbol,
        this.getHeaders(reqUser),
      );

      return result;
    } catch (error) {
      // Ideally status comes as a field on the error object if one is thrown (or on the result above)...
      // But this code doesn't get hit today. There is no 'status' on the error object.
      if (error?.status === 'NOT_FOUND') {
        return null;
      }

      // Errors come as JSON strings in the message...
      if (
        error?.message?.startsWith('Error: {') &&
        error?.message?.endsWith('}')
      ) {
        try {
          const errorJson = JSON.parse(
            error.message.substring('Error: '.length),
          );
          if (errorJson?.status === 'NOT_FOUND') {
            return null;
          }
        } catch (error2) {
          // Problem parsing JSON, throw the original error.
          throw error;
        }
      } else {
        throw error;
      }
    }

Multi instance initialization

One more thing I noticed is it seems the library works on a global scope, meaning 1 init function handles the library and any methods in the library will be under that. Can we make the library be more class based so that users may use multiple instances in the same code.

import { websockets } from 'polygon.io'

// Websockets Client:
const ws1 = websockets.Init({ apiKey: 'XXX' })
const stocksWs = ws1.getStocksWebsockets()

// Crypto Client:
const ws2 = websockets.Init({ apiKey: 'YYY' })
const cryptoWs = ws2.getCryptoWebsockets()

Websocket does not work as in tutorial!

ENV: Ubuntu 18, node v13.8.0

I copied the readme code for the websocket and when I run it I get:

Uncaught:
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received an instance of Object

It seems the websocket client you are using does not handle sending Objects directly, how is this fixed?

formatIQuoteV2Raw - wrong field for askPrice

Hi

according to website docs,
ask price would be P for quote object (IQuoteV2Raw)
and on formatIQuoteV2Raw function, you use raw.p for askPrice

file: v2HistoricQuotes.ts
Line 69: askPrice: raw.p, - should be raw.P

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.