Massive JS Client

repository·master·Indexed 42 days ago

https://github.com/massive-com/client-js

An isomorphic JavaScript client (v10.8.0) for interacting with Massive.com REST and WebSocket APIs. It provides typed interfaces for accessing financial market data across Stocks, Options, Indices, Futures, Forex, and Crypto. The library includes a unified MassiveClient that combines REST and WebSocket functionality, supports automatic pagination for REST calls, and provides specific WebSocket clients for real-time data like crypto and forex.

Tokens
10.1K
Snippets
31
Records
37
Agent score
54%

What's inside Massive

  1. Understand the client generation pipeline

    master

    The npm run generate command executes scripts/generate.sh, which follows these steps:

    1. Spec Retrieval: pull_spec.js downloads and filters the OpenAPI spec into src/openapi.json. It filters out draft paths, forces the default tag to ensure a single DefaultApi is emitted, and applies operation-id renames via operation-mappings.js.
    2. Code Generation: Uses openapi-generator-cli with the typescript-axios generator. It targets src/rest using custom templates located in templates/typescript-axios and applies specific flags: supportsES6, stringEnums, and useSingleRequestParameter.
    3. Existence Gate: The process aborts if src/rest/api.ts is not produced, preventing a partial or empty generation from overwriting the existing client.

    Note: Only files in src/rest are overwritten. Files in src/main.ts, src/websockets/, README.md, package.json, and templates/ are preserved.

  2. Enable automatic pagination

    master

    You can enable automatic pagination by passing pagination: true within the globalFetchOptions object when initializing the restClient. When enabled, the client will automatically follow next_url links in the API responses and return the accumulated data.

    import { restClient } from '@massive.com/client-js';
    
    const globalFetchOptions = {
    	pagination: true,
    };
    
    const rest = restClient(process.env.MASSIVE_API_KEY, "https://api.massive.com", globalFetchOptions);
    
    rest.getStocksAggregates({
      stocksTicker: "AAPL",
      multiplier: "1",
      timespan: "day",
      from: "2025-11-01",
      to: "2025-11-30"
    }).then((response) => {
    	const data = response.data; // convert axios-wrapped response
    	const resultCount = data.resultsCount;
    	console.log("Result count:", resultCount);
    }).catch(e => {
    	console.error('An error happened:', e);
    });
  3. Customize generated API via Template Overrides

    master

    To make permanent changes to the generated code, you must modify the templates in templates/typescript-axios/ rather than editing src/rest/** directly. The generator uses the -t flag to apply these local templates during the build.

    Key templates include:

    • apiInner.mustache: Controls the generated API surface.
    • common.mustache: Used to add an explicit Promise<R> return type to createRequestFunction. This is a workaround for an Axios issue (tracked as axios/axios#11116) where Axios >= 1.19 defaults a generic to a non-exported symbol, breaking TypeScript declaration emission.

    Warning: If you upgrade the openapi-generator version (pinned in openapitools.json), you must re-copy the new upstream templates and re-apply your local changes, or your customizations will be lost.

  4. Regenerate the Massive.com JS Client from OpenAPI spec

    master

    The TypeScript REST client is automatically generated from the Massive.com OpenAPI specification. While the REST endpoints in src/rest are generated, the WebSocket client (src/websockets/) and the main client glue (src/main.ts) are hand-written and are not affected by regeneration.

    To manually regenerate the client from the repository root, ensure you have the openapi-generator JDK on your PATH and that devDependencies are installed via npm ci.

    npm run generate
  5. Make REST API calls

    master

    Once initialized, use the rest instance to call API methods. Methods are mapped from the OpenAPI specification (e.g., getStocksAggregates, getLastStocksTrade, getLastStocksQuote, getStocksSnapshotTicker).

    import { restClient } from '@massive.com/client-js';
    
    const apiKey = "XXXX";
    const rest = restClient(apiKey, 'https://api.massive.com');
    
    async function example_getStocksAggregates() {
      try {
        const response = await rest.getStocksAggregates(
          {
            stocksTicker: "AAPL",
            multiplier: "1",
            timespan: "day",
            from: "2025-11-01",
            to: "2025-11-30",
            adjusted: "true",
            sort: "asc",
            limit: "120"
          }
        );
        console.log('Response:', response);
      } catch (e) {
        console.error('An error happened:', e);
      }
    }
    
    example_getStocksAggregates();
  6. Use the WebSocket Client

    master

    To use WebSockets, import websocketClient. You can access specific topic clients (like .stocks()) after initializing. Use .send() to subscribe to data and the .onmessage handler to process incoming events.

    import { websocketClient } from "@massive.com/client-js";
    
    const stocksWS = websocketClient(process.env.MASSIVE_API_KEY, 'wss://delayed.massive.com').stocks();
    
    stocksWS.onmessage = ({response}) => {
      const [message] = JSON.parse(response);
    
      // Example subscription
      stocksWS.send('{"action":"subscribe", "params":"AM.MSFT,A.MSFT"}');
    
      switch (message.ev) {
        case "AM":
          // handle trade message
          break;
        case "A":
          // handle trade message
          break;
      }
    };
    
    // Subscribe to a specific ticker
    stocksWS.send({ action: "subscribe", params: "T.MSFT" });
  7. Initialize the REST Client

    master

    Create a REST client instance by importing restClient and providing your API key. You can optionally specify a custom API base URL. By default, the client uses https://api.massive.com.

    import { restClient } from '@massive.com/client-js';
    
    // Basic initialization
    const rest = restClient(process.env.MASSIVE_API_KEY);
    
    // Initialization with custom base URL
    const rest = restClient(process.env.MASSIVE_API_KEY, 'https://api.massive.com');
  8. Reference: Client Generation Scripts

    master

    The following scripts are used to manage the client generation process:

    ScriptPurpose
    generate.shThe main orchestrator for the generation pipeline.
    pull_spec.jsDownloads and filters the OpenAPI spec to src/openapi.json.
    operation-mappings.jsMaps OpenAPI operation-ids to specific client-js method names. This file defines the public JS function names.
    generate-examples-with-tokens.jsA standalone developer tool that regenerates examples/rest/*.js from the spec. This is not part of the automated sync path.
  9. Initialize the Stocks WebSocket client with getStocksWebsocket()

    master

    Use getStocksWebsocket to establish a connection to the Massive.com stocks WebSocket stream. It requires an apiKey and accepts an optional apiBase URL (defaults to wss://socket.massive.com). The function returns a websocket.w3cwebsocket instance which you can use to listen for real-time stock events.

    import { getStocksWebsocket } from '@massive.com/client-js';
    
    const ws = getStocksWebsocket('YOUR_API_KEY');
    
    ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      console.log('Received stock event:', data);
    };
  10. Initialize the Options WebSocket client with getOptionsWebsocket()

    master

    Use getOptionsWebsocket to establish a connection to the Massive.com Options WebSocket stream. It requires an apiKey and accepts an optional apiBase URL (defaults to wss://socket.massive.com). The function returns a websocket.w3cwebsocket instance which you can use to listen for real-time options data events.

    import { getOptionsWebsocket } from '@massive.com/client-js';
    
    const ws = getOptionsWebsocket('YOUR_API_KEY');
    
    ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      console.log('Received options data:', data);
    };
    
    ws.onopen = () => console.log('Connected to Options WebSocket');
    ws.onerror = (err) => console.error('WebSocket error:', err);
  11. Configure the BaseAPI with custom settings

    master

    The BaseAPI class is the foundation for all REST API calls in the client. You can instantiate it with a Configuration object to override the default basePath or provide a custom AxiosInstance for specialized request handling (e.g., adding custom interceptors or middleware).

    import { BaseAPI } from '@massive.com/client-js';
    import { Configuration } from '@massive.com/client-js';
    import axios from 'axios';
    
    const config = new Configuration({ 
      basePath: 'https://custom-api.massive.com' 
    });
    
    // You can also pass a custom axios instance
    const customAxios = axios.create();
    const api = new BaseAPI(config, 'https://custom-api.massive.com', customAxios);