polygon-io / client-js Goto Github PK
View Code? Open in Web Editor NEWThe official JS client library for the Polygon REST and WebSocket API.
License: MIT License
The official JS client library for the Polygon REST and WebSocket API.
License: MIT License
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,
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×tamp=%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
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.
The reference methods dividends
, stockSplits
, and stockFinancials
in IReferenceClient
are all missing the corresponding IDividendsQuery
, IDividendsQuery
, and IStockFinancialQuery
query parameters.
Could you publish the v1.1.0 release to NPM please, or is there another reason its not available on there yet?
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)
});
Is there a timeline on adding /v1/indicators
to the client library?
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
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?
And if you request using the client, it gives a 404 which is not handled by the client which then throws an error.
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()
When using the import {restClient} from "@polygon.io/client-js"; I am getting an error that
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
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
In snapshot.d.ts
, todayChangePerc
should be todaysChangePerc
Hi,
When will the Last Quote for a Symbol v2 API be supported natively in the client library?
Thanks.
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.
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.
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?
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
export interface IDailyOpenClose {
afterhours?: number; <-- is supposed to be afterHours
close?: number;
from?: string;
hight?: number; <-- is supposed to be high
https://github.com/polygon-io/client-js/blob/master/src/rest/stocks/dailyOpenClose.ts#L9
IOptionsContractsResult
has a results?: IOptionsContractResults[]
property, but according to the Options Contract docs this should be an object rather than an array.
It's possible this was mixed up with the Options Contracts endpoint, which does have a results
array.
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
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;
In the package below fields are named incorrectly according to the related API doc page.
source_filling_url
should have been source_filing_url
filling_date
should have been filing_date
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
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)
Please do the needful
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
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 ;
}
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.
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.
[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.
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)
Hi, there is a typo on https://github.com/polygon-io/client-js/blob/master/src/rest/reference/marketHolidays.ts#L10 where it should be status
instead of staus
.
And there should be exchange
as well.
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.
#48 Introduced some breaking changes. The REST endpoints were updated to point to v2 for LastQuote and LastTrade but the ILastQuoteResult
and ILastTradeResult
return types were not updated in parallel.
Hi,
When will v3/reference/tickers be supported in the client library?
Thanks.
Add list
methods that paginate through next_url
.
This condition will never be validated
client-js/src/rest/transport/request.ts
Lines 17 to 26 in 613d87c
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.
I figured out that there are some missing props in the ticker details response.
ticker_root
address.postal_code
round_lot
Ref: https://github.com/polygon-io/client-js/blob/master/src/rest/reference/tickerDetails.ts
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.
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?
polygonClient
currently has the following definition:
Lines 7 to 10 in 9599e74
I think it's supposed to be websockets
, not websockers
๐
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.
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.
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;
}
}
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()
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?
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.