### Launch the Treemap Server Source: https://github.com/massive-com/client-python/blob/master/examples/tools/treemap/readme.md Navigate to the example directory and start the local visualization server. ```bash cd examples/tools/treemap python3 treemap_server.py ``` -------------------------------- ### Setup and Run Make Commands with Poetry Source: https://github.com/massive-com/client-python/blob/master/README.md Before running Make commands, especially if using pyenv, ensure you launch a Poetry shell and install dependencies. This sets up the correct Python environment for Make operations. ```shell poetry shell # start shell poetry install # install deps make test # run your make commands ``` -------------------------------- ### Install the Massive API Client Source: https://github.com/massive-com/client-python/blob/master/docs/source/Getting-Started.md Use pip to install the package. ```shell pip install massive-api-client ``` -------------------------------- ### Install Massive Python Client Source: https://github.com/massive-com/client-python/blob/master/README.md Use pip to install or update the library to the latest stable version. ```bash pip install -U massive ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/massive-com/client-python/blob/master/examples/tools/treemap/readme.md Install the required Massive.com Python client library. ```bash pip install -U massive-api-client ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/massive-com/client-python/blob/master/examples/tools/flatfiles-stock-trades/readme.md Installs necessary Python libraries for running the analysis scripts. Ensure you have Python 3 installed. ```bash pip install pandas matplotlib seaborn pytz ``` -------------------------------- ### GET /v3/reference/conditions Source: https://github.com/massive-com/client-python/blob/master/docs/source/Reference.md Lists market conditions. ```APIDOC ## GET /v3/reference/conditions ### Description Retrieves a list of market conditions for the specified asset class. ### Method GET ### Endpoint /v3/reference/conditions ``` -------------------------------- ### GET /v3/reference/exchanges Source: https://github.com/massive-com/client-python/blob/master/docs/source/Reference.md Lists market exchanges. ```APIDOC ## GET /v3/reference/exchanges ### Description Retrieves a list of exchanges for the specified asset class. ### Method GET ### Endpoint /v3/reference/exchanges ``` -------------------------------- ### Get Grouped Daily Bars Source: https://context7.com/massive-com/client-python/llms.txt Retrieve daily OHLC (Open, High, Low, Close) data for all tickers in a specified market on a given date. Supports filtering by market type and inclusion of OTC stocks. The example demonstrates processing top gainers by percentage change. ```python from massive import RESTClient client = RESTClient() # Get all stock daily bars for a date daily_bars = client.get_grouped_daily_aggs( date="2023-06-15", adjusted=True, locale="us", market_type="stocks", include_otc=False ) # Process top gainers by percentage change for bar in sorted(daily_bars, key=lambda x: (x.close - x.open) / x.open if x.open else 0, reverse=True)[:10]: pct_change = ((bar.close - bar.open) / bar.open * 100) if bar.open else 0 print(f"{bar.ticker}: {pct_change:.2f}% | Close: ${bar.close:.2f} | Volume: {bar.volume:,}") ``` -------------------------------- ### GET /v3/reference/tickers Source: https://github.com/massive-com/client-python/blob/master/docs/source/Reference.md Lists tickers for various asset classes. ```APIDOC ## GET /v3/reference/tickers ### Description Returns a list of tickers available for stocks, options, forex, or crypto. ### Method GET ### Endpoint /v3/reference/tickers ``` -------------------------------- ### WebSocket Client with Class-based State Management Source: https://github.com/massive-com/client-python/blob/master/docs/source/Getting-Started.md This example shows how to manage state within a callback by using a class instance. This is an alternative to using global variables for state. ```python from massive import WebSocketClient from massive.websocket.models import WebSocketMessage, EquityTrade from typing import List c = WebSocketClient(subscriptions=["T.*"]) class MessageHandler: count = 0 def handle_msg(self, msgs: List[WebSocketMessage]): for m in msgs: if type(m) == EquityTrade: print(self.count, m) self.count += 1 h = MessageHandler() def handle_msg(msgs: List[WebSocketMessage]): h.handle_msg(msgs) ``` -------------------------------- ### GET /v3/reference/splits Source: https://github.com/massive-com/client-python/blob/master/docs/source/Reference.md Lists stock splits. ```APIDOC ## GET /v3/reference/splits ### Description Retrieves a list of stock splits. ### Method GET ### Endpoint /v3/reference/splits ``` -------------------------------- ### Run Docker Container with Massive API Key Source: https://github.com/massive-com/client-python/blob/master/examples/tools/docker/readme.md Starts a Docker container from the 'massive-client-app' image and sets the 'MASSIVE_API_KEY' environment variable. Replace '' with your actual API key. ```bash docker run --env MASSIVE_API_KEY="" massive-client-app ``` -------------------------------- ### GET /list_snapshot_options_chain Source: https://context7.com/massive-com/client-python/llms.txt Retrieve the full options chain snapshot for an underlying asset. ```APIDOC ## GET /list_snapshot_options_chain ### Description Get the full options chain snapshot for an underlying asset. ### Parameters #### Query Parameters - **underlying_asset** (string) - Required - The underlying ticker - **params** (dict) - Optional - Filtering parameters (expiration_date, strike_price) ``` -------------------------------- ### GET /v3/reference/tickers/types Source: https://github.com/massive-com/client-python/blob/master/docs/source/Reference.md Lists supported ticker types. ```APIDOC ## GET /v3/reference/tickers/types ### Description Returns the available ticker types for the specified asset class. ### Method GET ### Endpoint /v3/reference/tickers/types ``` -------------------------------- ### GET /get_real_time_currency_conversion Source: https://context7.com/massive-com/client-python/llms.txt Convert currency amounts using real-time exchange rates. ```APIDOC ## GET /get_real_time_currency_conversion ### Description Convert currency amounts using real-time exchange rates. ### Parameters #### Query Parameters - **from_** (string) - Required - Source currency - **to** (string) - Required - Target currency - **amount** (float) - Required - Amount to convert - **precision** (integer) - Optional - Decimal precision ``` -------------------------------- ### GET /get_exchanges Source: https://context7.com/massive-com/client-python/llms.txt Retrieves information about supported exchanges. ```APIDOC ## GET /get_exchanges ### Description Retrieves information about supported exchanges. ### Parameters #### Query Parameters - **asset_class** (string) - Optional - Filter by asset class. - **locale** (string) - Optional - Filter by locale. ``` -------------------------------- ### GET /v3/reference/dividends Source: https://github.com/massive-com/client-python/blob/master/docs/source/Reference.md Lists stock dividends. ```APIDOC ## GET /v3/reference/dividends ### Description Retrieves a list of stock dividends. ### Method GET ### Endpoint /v3/reference/dividends ``` -------------------------------- ### Make Launchpad API Request with Required Headers Source: https://github.com/massive-com/client-python/blob/master/examples/launchpad/README.md Use this snippet to make an API request to Launchpad, ensuring all required edge headers are provided. This is the basic setup for Launchpad integration. ```python # import RESTClient from massive import RESTClient from massive.rest.models.request import RequestOptionBuilder # create client c = RESTClient(api_key="API_KEY") # create request options options = RequestOptionBuilder().edge_headers( edge_id="YOUR_EDGE_ID", # required edge_ip_address="IP_ADDRESS", # required ) # get response res = c.get_aggs("AAPL", 1, "day", "2022-04-04", "2022-04-04", options=options) # do something with response ``` -------------------------------- ### GET /vx/list_ipos Source: https://context7.com/massive-com/client-python/llms.txt Retrieves upcoming and historical IPO data (experimental vX endpoint). ```APIDOC ## GET /vx/list_ipos ### Description Retrieves upcoming and historical IPO data (experimental vX endpoint). ### Parameters #### Query Parameters - **ipo_status** (string) - Optional - Filter by IPO status (e.g., 'pending'). - **limit** (integer) - Optional - Number of results to return. ``` -------------------------------- ### GET /list_conditions Source: https://context7.com/massive-com/client-python/llms.txt Retrieves trading condition codes and their meanings. ```APIDOC ## GET /list_conditions ### Description Retrieves trading condition codes and their meanings. ### Parameters #### Query Parameters - **asset_class** (string) - Optional - Filter by asset class. - **data_type** (string) - Optional - Filter by data type. - **limit** (integer) - Optional - Number of results to return. ``` -------------------------------- ### Get Market Snapshots Source: https://context7.com/massive-com/client-python/llms.txt Retrieves real-time snapshot data including price and performance, with support for top gainers/losers and single ticker lookups. ```python from massive import RESTClient from massive.rest.models import SnapshotMarketType, Direction client = RESTClient() # Get snapshot for all stocks (paginated) snapshots = client.get_snapshot_all( market_type=SnapshotMarketType.STOCKS, tickers=["AAPL", "MSFT", "GOOGL"], include_otc=False ) for snap in snapshots: print(f"{snap.ticker}: ${snap.day.close:.2f} | Change: {snap.todays_change_perc:.2f}%") # Get top gainers gainers = client.get_snapshot_direction( market_type=SnapshotMarketType.STOCKS, direction=Direction.GAINERS ) print("\nTop Gainers:") for g in gainers[:5]: print(f"{g.ticker}: +{g.todays_change_perc:.2f}%") # Get top losers losers = client.get_snapshot_direction( market_type=SnapshotMarketType.STOCKS, direction=Direction.LOSERS ) print("\nTop Losers:") for l in losers[:5]: print(f"{l.ticker}: {l.todays_change_perc:.2f}%") # Get single ticker snapshot ticker_snap = client.get_snapshot_ticker( market_type=SnapshotMarketType.STOCKS, ticker="AAPL" ) print(f"\nAAPL Snapshot: ${ticker_snap.day.close:.2f}") ``` -------------------------------- ### GET /v3/reference/tickers/{ticker} Source: https://github.com/massive-com/client-python/blob/master/docs/source/Reference.md Retrieves detailed information for a specific ticker. ```APIDOC ## GET /v3/reference/tickers/{ticker} ### Description Provides detailed metadata for a specific ticker symbol. ### Method GET ### Endpoint /v3/reference/tickers/{ticker} ### Parameters #### Path Parameters - **ticker** (string) - Required - The ticker symbol to retrieve details for. ``` -------------------------------- ### GET /vx/list_stock_financials Source: https://context7.com/massive-com/client-python/llms.txt Retrieves historical financial data (experimental vX endpoint). ```APIDOC ## GET /vx/list_stock_financials ### Description Retrieves historical financial data (experimental vX endpoint). ### Parameters #### Query Parameters - **ticker** (string) - Required - The ticker symbol. - **timeframe** (string) - Optional - Financial timeframe (e.g., 'annual'). - **limit** (integer) - Optional - Number of results to return. ``` -------------------------------- ### GET /get_snapshot Source: https://context7.com/massive-com/client-python/llms.txt Retrieve real-time snapshot data for tickers, including price and performance. ```APIDOC ## GET /get_snapshot ### Description Get real-time snapshot data for tickers. ### Parameters #### Query Parameters - **market_type** (enum) - Required - Market type (STOCKS, etc.) - **tickers** (list) - Optional - List of tickers - **direction** (enum) - Optional - GAINERS or LOSERS - **ticker** (string) - Optional - Single ticker ``` -------------------------------- ### GET /v1/marketstatus/now Source: https://github.com/massive-com/client-python/blob/master/docs/source/Reference.md Retrieves the current market status for various asset classes. ```APIDOC ## GET /v1/marketstatus/now ### Description Retrieves the current operational status of the market for stocks, options, forex, or crypto. ### Method GET ### Endpoint /v1/marketstatus/now ``` -------------------------------- ### GET /get_market_status Source: https://context7.com/massive-com/client-python/llms.txt Checks if markets are currently open and retrieves trading hours. ```APIDOC ## GET /get_market_status ### Description Checks if markets are currently open and retrieves trading hours. ``` -------------------------------- ### GET /v2/reference/news Source: https://github.com/massive-com/client-python/blob/master/docs/source/Reference.md Lists news articles related to specific tickers. ```APIDOC ## GET /v2/reference/news ### Description Retrieves news articles associated with specific tickers. ### Method GET ### Endpoint /v2/reference/news ``` -------------------------------- ### Get Daily Open/Close Aggregates Source: https://context7.com/massive-com/client-python/llms.txt Fetch the daily open, close, and after-hours prices for a specific ticker on a given date. The response includes pre-market and after-hours data if available. ```python from massive import RESTClient client = RESTClient() # Get daily open/close for AAPL ohlc = client.get_daily_open_close_agg( ticker="AAPL", date="2023-06-15", adjusted=True ) print(f"Ticker: {ohlc.symbol}") print(f"Open: ${ohlc.open:.2f}") print(f"High: ${ohlc.high:.2f}") print(f"Low: ${ohlc.low:.2f}") print(f"Close: ${ohlc.close:.2f}") print(f"Pre-market: ${ohlc.preMarket:.2f}" if ohlc.preMarket else "No pre-market data") print(f"After-hours: ${ohlc.afterHours:.2f}" if ohlc.afterHours else "No after-hours data") ``` -------------------------------- ### Get Crypto Order Book (Level 2) Source: https://context7.com/massive-com/client-python/llms.txt Fetch the full Level 2 order book for a given cryptocurrency pair. This provides a detailed view of buy and sell orders. ```python from massive import RESTClient client = RESTClient() # Get L2 order book for BTC/USD book = client.get_snapshot_crypto_book(ticker="X:BTCUSD") print(f"Ticker: {book.ticker}") print(f"\nTop 5 Bids:") for bid in book.bids[:5]: print(f" ${bid['p']:.2f} x {bid['x']}") print(f"\nTop 5 Asks:") for ask in book.asks[:5]: print(f" ${ask['p']:.2f} x {ask['x']}") ``` -------------------------------- ### GET /v1/marketstatus/upcoming Source: https://github.com/massive-com/client-python/blob/master/docs/source/Reference.md Retrieves upcoming market holidays for various asset classes. ```APIDOC ## GET /v1/marketstatus/upcoming ### Description Retrieves a list of upcoming market holidays for stocks, options, forex, or crypto. ### Method GET ### Endpoint /v1/marketstatus/upcoming ``` -------------------------------- ### Get Single Option Contract Snapshot Source: https://context7.com/massive-com/client-python/llms.txt Retrieves a detailed snapshot for a specific option contract. ```python from massive import RESTClient client = RESTClient() ``` -------------------------------- ### Handle WebSocket Messages Source: https://github.com/massive-com/client-python/blob/master/README.md Define a handler function to process incoming messages and start the WebSocket connection. ```python def handle_msg(msg: List[WebSocketMessage]): for m in msg: print(m) ws.run(handle_msg=handle_msg) ``` -------------------------------- ### Get Option Contract Snapshot Source: https://context7.com/massive-com/client-python/llms.txt Retrieve a snapshot of data for a specific option contract. Requires the underlying asset and the option contract identifier. ```python option_snap = client.get_snapshot_option( underlying_asset="AAPL", option_contract="O:AAPL230616C00180000" ) print(f"Contract: {option_snap.details.ticker}") print(f"Strike: ${option_snap.details.strike_price}") print(f"Expiration: {option_snap.details.expiration_date}") print(f"Last Price: ${option_snap.day.close:.2f}") print(f"Open Interest: {option_snap.open_interest}") if option_snap.greeks: print(f"Greeks - Delta: {option_snap.greeks.delta:.4f}, Gamma: {option_snap.greeks.gamma:.4f}") ``` -------------------------------- ### Get Ticker Details Source: https://context7.com/massive-com/client-python/llms.txt Retrieve comprehensive details for a specific ticker, including company information, market capitalization, and primary exchange. ```python from massive import RESTClient client = RESTClient() # Get detailed information about AAPL details = client.get_ticker_details(ticker="AAPL") print(f"Name: {details.name}") print(f"Ticker: {details.ticker}") print(f"Market Cap: ${details.market_cap:,.0f}" if details.market_cap else "N/A") print(f"Employees: {details.total_employees:,}" if details.total_employees else "N/A") print(f"Exchange: {details.primary_exchange}") print(f"Homepage: {details.homepage_url}") print(f"Description: {details.description[:200]}" if details.description else "N/A") ``` -------------------------------- ### List Exchanges Source: https://context7.com/massive-com/client-python/llms.txt Get information about supported financial exchanges, filtering by asset class (e.g., stocks) and locale (e.g., US). ```python exchanges = client.get_exchanges( asset_class=AssetClass.STOCKS, locale=Locale.US ) for exchange in exchanges: print(f"{exchange.mic}: {exchange.name} ({exchange.type})") ``` -------------------------------- ### Get Ticker Details Source: https://context7.com/massive-com/client-python/llms.txt Retrieves comprehensive details about a specific ticker, including company information, market capitalization, and description. ```APIDOC ## GET /api/ticker/details ### Description Get comprehensive details about a specific ticker including company information. ### Method GET ### Endpoint `/api/ticker/details` ### Query Parameters - **ticker** (string) - Required - The ticker symbol (e.g., AAPL). ### Response #### Success Response (200) - **name** (string) - The name of the company or asset. - **ticker** (string) - The ticker symbol. - **market_cap** (number) - The market capitalization. - **total_employees** (integer) - The total number of employees. - **primary_exchange** (string) - The primary exchange where the ticker is listed. - **homepage_url** (string) - The URL of the company's homepage. - **description** (string) - A description of the company or asset. ### Response Example ```json { "name": "Apple Inc.", "ticker": "AAPL", "market_cap": 2800000000000, "total_employees": 164000, "primary_exchange": "NASDAQ", "homepage_url": "https://www.apple.com", "description": "Apple Inc. is an American multinational technology company..." } ``` ``` -------------------------------- ### Get Market Holidays Source: https://context7.com/massive-com/client-python/llms.txt Retrieve a list of upcoming market holidays, including their dates, names, and whether the market will be closed or open with specific trading hours. ```python holidays = client.get_market_holidays() for holiday in holidays[:5]: status = "Closed" if holiday.status == "closed" else f"Open {holiday.open} - {holiday.close}" print(f"{holiday.date}: {holiday.name} - {status}") ``` -------------------------------- ### Get Market Status Source: https://context7.com/massive-com/client-python/llms.txt Check the current status of financial markets, including whether they are open and the trading hours for major exchanges like NYSE and NASDAQ. ```python status = client.get_market_status() print(f"Market Status: {status.market}") print(f"NYSE: {status.exchanges.nyse}") print(f"NASDAQ: {status.exchanges.nasdaq}") print(f"Extended Hours: Early Trading={status.early_hours}, After Hours={status.after_hours}") ``` -------------------------------- ### Initialize RESTClient Source: https://github.com/massive-com/client-python/blob/master/README.md Create a new client instance using your API key. ```python client = RESTClient(api_key="") ``` -------------------------------- ### REST API Client Initialization Source: https://github.com/massive-com/client-python/blob/master/README.md How to import and initialize the RESTClient using your API key. ```APIDOC ## Initialization ### Description Import the RESTClient and initialize it with your API key to begin making requests. ### Request Example ```python from massive import RESTClient client = RESTClient(api_key="") ``` ``` -------------------------------- ### Initialize WebSocket Client Source: https://github.com/massive-com/client-python/blob/master/README.md Create a WebSocket client instance with an API key and a list of ticker subscriptions. ```python # Note: Multiple subscriptions can be added to the array # For example, if you want to subscribe to AAPL and META, # you can do so by adding "T.META" to the subscriptions array. ["T.AAPL", "T.META"] # If you want to subscribe to all tickers, place an asterisk in place of the symbol. ["T.*"] ws = WebSocketClient(api_key=, subscriptions=["T.AAPL"]) ``` -------------------------------- ### Get Previous Close Aggregate Source: https://context7.com/massive-com/client-python/llms.txt Retrieve the previous day's OHLC (Open, High, Low, Close) data for one or more tickers. The `adjusted` parameter can be used to get adjusted prices. ```python from massive import RESTClient client = RESTClient() # Get previous close for multiple tickers tickers = ["AAPL", "MSFT", "GOOGL", "AMZN", "META"] for ticker in tickers: prev = client.get_previous_close_agg(ticker=ticker, adjusted=True) print(f"{ticker}: Close=${prev.close:.2f} Volume={prev.volume:,}") ``` -------------------------------- ### Initialize WebSocket Client for Stocks Source: https://context7.com/massive-com/client-python/llms.txt Connects to the real-time stock market feed and handles incoming trade and quote messages. Requires API key or environment variable. ```python from massive import WebSocketClient from massive.websocket.models import WebSocketMessage, Market, Feed from typing import List # Initialize WebSocket client for stocks ws = WebSocketClient( api_key="your_api_key", # or use MASSIVE_API_KEY env var feed=Feed.RealTime, market=Market.Stocks, subscriptions=["T.AAPL", "Q.AAPL"] # Trades and Quotes for AAPL ) def handle_msg(msgs: List[WebSocketMessage]): for msg in msgs: if hasattr(msg, 'price'): # Trade message print(f"Trade: {msg.symbol} @ ${msg.price:.2f} x {msg.size}") elif hasattr(msg, 'bid_price'): # Quote message print(f"Quote: {msg.symbol} Bid=${msg.bid_price:.2f} Ask=${msg.ask_price:.2f}") # Run synchronously (blocking) ws.run(handle_msg) ``` -------------------------------- ### Clone the Repository Source: https://github.com/massive-com/client-python/blob/master/examples/tools/treemap/readme.md Download the project source code from GitHub. ```bash git clone https://github.com/massive-com/client-python.git ``` -------------------------------- ### Initialize and Draw Vis Network Source: https://github.com/massive-com/client-python/blob/master/examples/tools/related-companies/index.html Sets up the nodes and edges data structures and initializes the Vis.js network instance within the specified container. ```javascript var nodes = null; var edges = null; var network = null; function draw() { nodes = [{"id": 1, "label": "MSFT"}, {"id": 2, "label": "GOOGL"}, {"id": 3, "label": "NVDA"}, {"id": 4, "label": "AMZN"}, {"id": 5, "label": "GOOG"}, {"id": 6, "label": "META"}, {"id": 7, "label": "TSLA"}, {"id": 8, "label": "AAPL"}, {"id": 9, "label": "CRM"}, {"id": 10, "label": "ORCL"}, {"id": 11, "label": "AMD"}, {"id": 12, "label": "NFLX"}, {"id": 13, "label": "WMT"}, {"id": 14, "label": "DIS"}, {"id": 15, "label": "SNAP"}, {"id": 16, "label": "SHOP"}, {"id": 17, "label": "INTC"}, {"id": 18, "label": "ANET"}, {"id": 19, "label": "RIVN"}, {"id": 20, "label": "GM"}, {"id": 21, "label": "F"}, {"id": 22, "label": "LCID"}, {"id": 23, "label": "GME"}, {"id": 24, "label": "AMC"}, {"id": 25, "label": "HOOD"}, {"id": 26, "label": "BB"}, {"id": 27, "label": "CHWY"}, {"id": 28, "label": "CLOV"}, {"id": 29, "label": "PLTR"}, {"id": 30, "label": "SNDL"}, {"id": 31, "label": "WBD"}, {"id": 32, "label": "CMCSA"}, {"id": 33, "label": "PARA"}, {"id": 34, "label": "T"}, {"id": 35, "label": "ROKU"}]; edges = [{"from": 1, "to": 2}, {"from": 1, "to": 3}, {"from": 1, "to": 4}, {"from": 1, "to": 5}, {"from": 1, "to": 6}, {"from": 1, "to": 7}, {"from": 1, "to": 8}, {"from": 1, "to": 9}, {"from": 1, "to": 10}, {"from": 1, "to": 11}, {"from": 4, "to": 1}, {"from": 4, "to": 2}, {"from": 4, "to": 5}, {"from": 4, "to": 8}, {"from": 4, "to": 7}, {"from": 4, "to": 3}, {"from": 4, "to": 6}, {"from": 4, "to": 12}, {"from": 4, "to": 13}, {"from": 4, "to": 14}, {"from": 6, "to": 5}, {"from": 6, "to": 2}, {"from": 6, "to": 1}, {"from": 6, "to": 4}, {"from": 6, "to": 8}, {"from": 6, "to": 7}, {"from": 6, "to": 3}, {"from": 6, "to": 15}, {"from": 6, "to": 12}, {"from": 6, "to": 11}, {"from": 8, "to": 1}, {"from": 8, "to": 2}, {"from": 8, "to": 4}, {"from": 8, "to": 5}, {"from": 8, "to": 7}, {"from": 8, "to": 3}, {"from": 8, "to": 6}, {"from": 8, "to": 12}, {"from": 8, "to": 14}, {"from": 8, "to": 11}, {"from": 5, "to": 2}, {"from": 5, "to": 1}, {"from": 5, "to": 6}, {"from": 5, "to": 4}, {"from": 5, "to": 8}, {"from": 5, "to": 7}, {"from": 5, "to": 3}, {"from": 5, "to": 15}, {"from": 5, "to": 12}, {"from": 5, "to": 16}, {"from": 3, "to": 11}, {"from": 3, "to": 6}, {"from": 3, "to": 2}, {"from": 3, "to": 7}, {"from": 3, "to": 5}, {"from": 3, "to": 1}, {"from": 3, "to": 8}, {"from": 3, "to": 4}, {"from": 3, "to": 17}, {"from": 3, "to": 18}, {"from": 7, "to": 19}, {"from": 7, "to": 2}, {"from": 7, "to": 4}, {"from": 7, "to": 20}, {"from": 7, "to": 21}, {"from": 7, "to": 22}, {"from": 7, "to": 5}, {"from": 7, "to": 6}, {"from": 7, "to": 8}, {"from": 7, "to": 3}, {"from": 23, "to": 24}, {"from": 23, "to": 7}, {"from": 23, "to": 25}, {"from": 23, "to": 26}, {"from": 23, "to": 27}, {"from": 23, "to": 28}, {"from": 23, "to": 4}, {"from": 23, "to": 29}, {"from": 23, "to": 2}, {"from": 23, "to": 30}, {"from": 14, "to": 12}, {"from": 14, "to": 31}, {"from": 14, "to": 4}, {"from": 14, "to": 32}, {"from": 14, "to": 33}, {"from": 14, "to": 8}, {"from": 14, "to": 2}, {"from": 14, "to": 34}, {"from": 14, "to": 5}, {"from": 14, "to": 35}]; var container = document.getElementById("mynetwork"); var data = { nodes: nodes, edges: edges }; var options = { nodes: { shape: 'dot' } }; network = new vis.Network(container, data, options); } ``` -------------------------------- ### Initialize REST Client Source: https://context7.com/massive-com/client-python/llms.txt Initialize the REST client with your API key. The API key can be provided directly or set as an environment variable. Custom connection and read timeouts, connection pools, retries, and verbose logging can also be configured. ```python from massive import RESTClient import os # Option 1: Use environment variable (recommended) # export MASSIVE_API_KEY="your_api_key" client = RESTClient() ``` ```python client = RESTClient(api_key="your_api_key") ``` ```python client = RESTClient( api_key="your_api_key", connect_timeout=10.0, read_timeout=10.0, num_pools=10, retries=3, pagination=True, # Auto-paginate results (default: True) verbose=True, # Enable logging trace=True # Enable request/response tracing for debugging ) ``` -------------------------------- ### Initialize the RESTClient Source: https://github.com/massive-com/client-python/blob/master/docs/source/Getting-Started.md The client can automatically use the MASSIVE_API_KEY environment variable or accept an API key as a constructor argument. ```python from massive import RESTClient client = RESTClient() # MASSIVE_API_KEY is used client = RESTClient("api_key") # api_key is used ``` -------------------------------- ### Download Historical Stock Data with MinIO Client Source: https://github.com/massive-com/client-python/blob/master/examples/tools/hunting-anomalies/README.md Use the MinIO client to download historical stock market data. Adjust commands and paths based on your data interests. Ensure data is decompressed after download. ```bash mc alias set s3massive https://files.massive.com YOUR_ACCESS_KEY YOUR_SECRET_KEY ``` ```bash mc cp --recursive s3massive/flatfiles/us_stocks_sip/day_aggs_v1/2024/08/ ./aggregates_day/ ``` ```bash mc cp --recursive s3massive/flatfiles/us_stocks_sip/day_aggs_v1/2024/09/ ./aggregates_day/ ``` ```bash mc cp --recursive s3massive/flatfiles/us_stocks_sip/day_aggs_v1/2024/10/ ./aggregates_day/ ``` ```bash gunzip ./aggregates_day/*.gz ``` -------------------------------- ### GET /get_market_holidays Source: https://context7.com/massive-com/client-python/llms.txt Retrieves upcoming market holidays and trading hours. ```APIDOC ## GET /get_market_holidays ### Description Retrieves upcoming market holidays and trading hours. ``` -------------------------------- ### GET /list_dividends Source: https://context7.com/massive-com/client-python/llms.txt Retrieves historical dividend data for a specific ticker. ```APIDOC ## GET /list_dividends ### Description Retrieves historical dividend data for a specific ticker. ### Method GET ### Parameters #### Query Parameters - **ticker** (string) - Required - The ticker symbol. - **order** (string) - Optional - Sort order. - **limit** (integer) - Optional - Number of results to return. ``` -------------------------------- ### Make Launchpad API Request with Optional User Agent Source: https://github.com/massive-com/client-python/blob/master/examples/launchpad/README.md This snippet extends the basic Launchpad API request by including an optional User Agent header. This allows for specifying the origination of the Edge User's request. ```python # import RESTClient from massive import RESTClient from massive.rest.models.request import RequestOptionBuilder # create client c = RESTClient(api_key="API_KEY") # create request options options = RequestOptionBuilder().edge_headers( edge_id="YOUR_EDGE_ID", # required edge_ip_address="IP_ADDRESS" # required ).update_edge_header( edge_user="EDGE_USER" # optional ) # get response res = c.get_aggs("AAPL", 1, "day", "2022-04-04", "2022-04-04", options=options) # do something with response ``` -------------------------------- ### GET /get_last_trade Source: https://context7.com/massive-com/client-python/llms.txt Retrieve the most recent trade for a stock or crypto asset. ```APIDOC ## GET /get_last_trade ### Description Get the most recent trade for a ticker or crypto pair. ### Parameters #### Query Parameters - **ticker** (string) - Optional - Stock ticker symbol - **from_** (string) - Optional - Crypto base currency - **to** (string) - Optional - Crypto quote currency ``` -------------------------------- ### REST Client - Pagination Control Source: https://context7.com/massive-com/client-python/llms.txt Demonstrates using the REST client with auto-pagination enabled to fetch all records for a given request, such as all trades for a specific day. The `limit` parameter controls the page size, not the total number of records fetched. ```python from massive import RESTClient # Default: auto-pagination enabled (fetches all pages) client = RESTClient(pagination=True) # Get ALL trades for a day (may be millions) all_trades = list(client.list_trades( ticker="AAPL", timestamp="2023-06-15", limit=50000 # Page size, not total limit )) print(f"Total trades: {len(all_trades)}") ``` -------------------------------- ### Build Lookup Table from Historical Data Source: https://github.com/massive-com/client-python/blob/master/examples/tools/hunting-anomalies/README.md Process downloaded historical data to build a lookup table. This script saves the processed data as 'lookup_table.pkl'. ```python python build-lookup-table.py ``` -------------------------------- ### Configure API Key Source: https://github.com/massive-com/client-python/blob/master/examples/tools/treemap/readme.md Set the Massive.com API key as an environment variable for authentication. ```bash export MASSIVE_API_KEY=YOUR_API_KEY_HERE ``` -------------------------------- ### Run GUI for Visual Anomaly Exploration Source: https://github.com/massive-com/client-python/blob/master/examples/tools/hunting-anomalies/README.md Launch a browser-based interface to visually explore detected anomalies. Access the GUI at http://localhost:8888. ```python python gui-lookup-table.py ``` -------------------------------- ### Build Docker Image for Massive Client App Source: https://github.com/massive-com/client-python/blob/master/examples/tools/docker/readme.md Builds a Docker image named 'massive-client-app' from the Dockerfile in the current directory. Rebuild the image whenever the Python script is updated. ```bash docker build -t massive-client-app . ``` -------------------------------- ### GET /list_splits Source: https://context7.com/massive-com/client-python/llms.txt Retrieves historical stock split data for a specific ticker. ```APIDOC ## GET /list_splits ### Description Retrieves historical stock split data for a specific ticker. ### Method GET ### Parameters #### Query Parameters - **ticker** (string) - Required - The ticker symbol to retrieve splits for. - **order** (string) - Optional - Sort order (e.g., 'desc'). - **limit** (integer) - Optional - Number of results to return. ``` -------------------------------- ### WebSocket Client - Real-Time Stocks Source: https://context7.com/massive-com/client-python/llms.txt Connect to real-time stock market data streams using the WebSocket client. Requires importing specific models for messages, markets, and feeds. ```python from massive import WebSocketClient from massive.websocket.models import WebSocketMessage, Market, Feed from typing import List ``` -------------------------------- ### Options Chain Snapshot Source: https://context7.com/massive-com/client-python/llms.txt Retrieves an options chain for an underlying asset with filtering parameters for expiration and strike price. ```python from massive import RESTClient client = RESTClient() # Get options chain for AAPL with filters options_chain = [] for option in client.list_snapshot_options_chain( underlying_asset="AAPL", params={ "expiration_date.gte": "2024-03-16", "strike_price.gte": 170, "strike_price.lte": 200, } ): options_chain.append(option) print(f"Found {len(options_chain)} option contracts") for opt in options_chain[:5]: print(f"{opt.details.ticker}: Strike=${opt.details.strike_price} Exp={opt.details.expiration_date}") if opt.greeks: print(f" Delta: {opt.greeks.delta:.4f} | IV: {opt.implied_volatility:.2%}") ``` -------------------------------- ### GET /get_last_quote Source: https://context7.com/massive-com/client-python/llms.txt Retrieve the most recent NBBO quote for a stock or forex pair. ```APIDOC ## GET /get_last_quote ### Description Get the most recent NBBO quote for a ticker or forex pair. ### Parameters #### Query Parameters - **ticker** (string) - Optional - Stock ticker - **from_** (string) - Optional - Forex base currency - **to** (string) - Optional - Forex quote currency ``` -------------------------------- ### WebSocket Client - Async Connection Source: https://context7.com/massive-com/client-python/llms.txt Establishes an asynchronous WebSocket connection for real-time stock data, allowing for non-blocking message handling. Supports automatic reconnection with a specified limit. ```python import asyncio from massive import WebSocketClient from massive.websocket.models import WebSocketMessage, Market, Feed from typing import List async def main(): ws = WebSocketClient( feed=Feed.RealTime, market=Market.Stocks, subscriptions=["A.AAPL"], # Per-second aggregates max_reconnects=5 ) async def handle_msg(msgs: List[WebSocketMessage]): for msg in msgs: print(f"Agg: {msg.symbol} O={msg.open} H={msg.high} L={msg.low} C={msg.close} V={msg.volume}") # Connect and process messages try: await ws.connect(handle_msg) except KeyboardInterrupt: await ws.close() asyncio.run(main()) ``` -------------------------------- ### GET /get_related_companies Source: https://context7.com/massive-com/client-python/llms.txt Finds companies related to a ticker based on news and returns data. ```APIDOC ## GET /get_related_companies ### Description Finds companies related to a ticker based on news and returns data. ### Parameters #### Query Parameters - **ticker** (string) - Required - The ticker symbol. ``` -------------------------------- ### Configure Pagination Behavior Source: https://github.com/massive-com/client-python/blob/master/README.md Control how the client handles result pagination by toggling the pagination parameter. ```python client = RESTClient(api_key="") trades = [t for t in client.list_trades(ticker="TSLA", limit=100)] ``` ```python client = RESTClient(api_key="", pagination=False) trades = [t for t in client.list_trades(ticker="TSLA", limit=100)] ``` -------------------------------- ### GET /list_options_contracts Source: https://context7.com/massive-com/client-python/llms.txt Retrieves options contracts for an underlying ticker based on various filters. ```APIDOC ## GET /list_options_contracts ### Description Retrieves options contracts for an underlying ticker based on various filters. ### Method GET ### Parameters #### Query Parameters - **underlying_ticker** (string) - Required - The underlying ticker symbol. - **contract_type** (string) - Optional - Type of contract (e.g., 'call'). - **expiration_date_gte** (string) - Optional - Filter by expiration date greater than or equal to. - **expiration_date_lte** (string) - Optional - Filter by expiration date less than or equal to. - **strike_price_gte** (number) - Optional - Filter by strike price greater than or equal to. - **strike_price_lte** (number) - Optional - Filter by strike price less than or equal to. - **expired** (boolean) - Optional - Include expired contracts. - **limit** (integer) - Optional - Number of results to return. ``` -------------------------------- ### Import RESTClient Source: https://github.com/massive-com/client-python/blob/master/README.md Import the RESTClient class from the massive package. ```python from massive import RESTClient ``` -------------------------------- ### List Universal Snapshots Source: https://context7.com/massive-com/client-python/llms.txt Retrieves snapshots across multiple asset types using a list of tickers. ```python from massive import RESTClient from massive.rest.models import SnapshotMarketType client = RESTClient() # Get snapshots for multiple tickers across markets snapshots = list(client.list_universal_snapshots( ticker_any_of=["AAPL", "O:AAPL230616C00180000", "X:BTCUSD"], limit=50 )) for snap in snapshots: print(f"{snap.ticker} ({snap.type}): ${snap.session.close if snap.session else 'N/A'}") ``` -------------------------------- ### Get Last Quote Source: https://context7.com/massive-com/client-python/llms.txt Retrieves the most recent NBBO quote for stocks or forex pairs. ```python from massive import RESTClient client = RESTClient() # Get last quote for a stock last_quote = client.get_last_quote(ticker="AAPL") print(f"Bid: ${last_quote.bid_price:.2f} x {last_quote.bid_size}") print(f"Ask: ${last_quote.ask_price:.2f} x {last_quote.ask_size}") # Get last forex quote forex_quote = client.get_last_forex_quote(from_="EUR", to="USD") print(f"EUR/USD - Bid: {forex_quote.bid:.5f} | Ask: {forex_quote.ask:.5f}") ``` -------------------------------- ### Get Last Trade Source: https://context7.com/massive-com/client-python/llms.txt Retrieves the most recent trade data for stocks or crypto assets. ```python from massive import RESTClient client = RESTClient() # Get last trade for a stock last_trade = client.get_last_trade(ticker="AAPL") print(f"Last Trade: ${last_trade.price:.2f} | Size: {last_trade.size}") print(f"Exchange: {last_trade.exchange} | Timestamp: {last_trade.sip_timestamp}") # Get last crypto trade crypto_trade = client.get_last_crypto_trade(from_="BTC", to="USD") print(f"BTC/USD: ${crypto_trade.price:.2f} | Size: {crypto_trade.size}") ``` -------------------------------- ### Experimental: List IPOs Source: https://context7.com/massive-com/client-python/llms.txt Fetch upcoming and historical Initial Public Offering (IPO) data, including pending IPOs with details like issuer name and price range. This uses an experimental vX endpoint. ```python ipos = list(client.vx.list_ipos( ipo_status="pending", limit=10 )) for ipo in ipos: print(f"{ipo.ticker}: {ipo.issuer_name}") print(f" Expected Date: {ipo.listing_date}") print(f" Price Range: ${ipo.min_shares_offered_price} - ${ipo.max_shares_offered_price}") ``` -------------------------------- ### GET /list_quotes Source: https://context7.com/massive-com/client-python/llms.txt Retrieve historical National Best Bid and Offer (NBBO) quotes for a ticker. ```APIDOC ## GET /list_quotes ### Description Get historical NBBO quotes for a ticker. ### Parameters #### Query Parameters - **ticker** (string) - Required - The ticker symbol - **timestamp** (string) - Required - Date for quotes - **limit** (integer) - Optional - Limit results - **sort** (string) - Optional - Sort field - **order** (string) - Optional - Sort order (asc/desc) ``` -------------------------------- ### GET /list_trades Source: https://context7.com/massive-com/client-python/llms.txt Retrieve a list of trades for a specific ticker within a defined timestamp range. ```APIDOC ## GET /list_trades ### Description Filter and retrieve trades for a specific ticker within a timestamp range. ### Parameters #### Query Parameters - **ticker** (string) - Required - The ticker symbol (e.g., TSLA) - **timestamp_gte** (string) - Required - Start timestamp (ISO format) - **timestamp_lt** (string) - Required - End timestamp (ISO format) - **limit** (integer) - Optional - Maximum number of trades to return ``` -------------------------------- ### Import WebSocket Client Classes Source: https://github.com/massive-com/client-python/blob/master/README.md Required imports for utilizing the WebSocket client and handling incoming messages. ```python from massive import WebSocketClient from massive.websocket.models import WebSocketMessage from typing import List ``` -------------------------------- ### Get Related Companies Source: https://context7.com/massive-com/client-python/llms.txt Find companies that are related to a given ticker based on news and return data analysis. ```python related = client.get_related_companies(ticker="AAPL") print(f"Companies related to AAPL:") for company in related: print(f" {company.ticker}") ``` -------------------------------- ### Asynchronous WebSocket Client with asyncio Source: https://github.com/massive-com/client-python/blob/master/docs/source/Getting-Started.md Manage the WebSocket client's asynchronous runtime manually using asyncio. This allows for finer control over connection, subscription, and disconnection. ```python from massive import WebSocketClient from massive.websocket.models import WebSocketMessage from typing import List import asyncio c = WebSocketClient(subscriptions=["T.*"]) async def handle_msg(msgs: List[WebSocketMessage]): for m in msgs: print(m) async def timeout(): await asyncio.sleep(1) print("unsubscribe_all") c.unsubscribe_all() await asyncio.sleep(1) print("close") await c.close() async def main(): await asyncio.gather(c.connect(handle_msg), timeout()) asyncio.run(main()) ``` -------------------------------- ### Access the Visualization Source: https://github.com/massive-com/client-python/blob/master/examples/tools/treemap/readme.md URL to access the running Treemap visualization in a web browser. ```text http://localhost:8889 ``` -------------------------------- ### WebSocket Client - Forex Market Source: https://context7.com/massive-com/client-python/llms.txt Streams real-time forex currency pair data, processing quotes and aggregates to calculate and display the spread between bid and ask prices. ```python from massive import WebSocketClient from massive.websocket.models import WebSocketMessage, Market, Feed from typing import List ws = WebSocketClient( feed=Feed.RealTime, market=Market.Forex, subscriptions=[ "C.C:EURUSD", # EUR/USD quotes "CA.C:EURUSD", # EUR/USD aggregates "C.C:GBPUSD" # GBP/USD quotes ] ) def handle_msg(msgs: List[WebSocketMessage]): for msg in msgs: if hasattr(msg, 'bid') and hasattr(msg, 'ask'): spread = msg.ask - msg.bid print(f"{msg.pair}: Bid={msg.bid:.5f} Ask={msg.ask:.5f} Spread={spread:.5f}") ws.run(handle_msg) ``` -------------------------------- ### List Stock Financials using vX Source: https://github.com/massive-com/client-python/blob/master/docs/source/vX.md Call the list_stock_financials method via the vx class member on RESTClient to retrieve stock financial data. ```python financials = RESTClient().vx.list_stock_financials() ``` -------------------------------- ### Basic WebSocket Client Usage Source: https://github.com/massive-com/client-python/blob/master/docs/source/Getting-Started.md Use this snippet for simple message handling by providing a callback function to the WebSocketClient. Raises AuthError if an invalid API key is provided. ```python from massive import WebSocketClient from massive.websocket.models import WebSocketMessage from typing import List c = WebSocketClient(subscriptions=["T.*"]) def handle_msg(msgs: List[WebSocketMessage]): for m in msgs: print(m) c.run(handle_msg) ``` -------------------------------- ### Retrieve Data from Non-Paginated Endpoints Source: https://github.com/massive-com/client-python/blob/master/docs/source/Getting-Started.md Use the get_* methods to fetch data from non-paginated endpoints. ```python from massive import RESTClient from massive.rest import models client = RESTClient() aggs = client.get_aggs( "AAPL", 1, "day", "2022-04-04", "2022-04-04", ) print(aggs) ```