Accelpix Realtime APIs - Realtime and Historical Data in Python

Pix APIs - Realtime and Historical Data in Python

Introduction

AccelPix Data API is a Python library designed to connect and stream market data seamlessly. Leveraging WebSocket and fallback transport mechanisms, this library provides functionalities to access both End of Day (EOD) and live streaming data with ease. It ensures simple and straightforward integration with your web applications, handling all the heavy lifting behind the scenes.


What's New

v1.3.5 (13-12-2024)

  • Bug fixes

v1.3.4 (11-Dec-2024)

  • Removed scheme parameter from the initialize method
  • Updated library tree to the latest version

v1.3.3 (29-Aug-2022)

  • Added Option Chain and Option Chain Range subscription and unsubscription methods

v1.3.2 (02-Aug-2022)

  • Introduced Option Chain subscription and unsubscription methods

v1.3.1 (28-Jan-2022)

  • Added a new callback for Trade snapshots during subscription (previously provided along with Trade callback)
  • Enabled Segment subscription for entitled users
  • Introduced Option Greeks

v1.3.0 (06-May-2021)

  • Added upper and lower price bands for the EQ market (refer to the Refs Snapshot Data section)
  • Implemented live ticks aggregation providing current day minute bars (refer to the History Data - Intra-Day section)

Installation

Install the AccelPix Data API library using pip:

  1. pip install pix-apidata

Quick Start

For Streaming Data:

  1. Initialize the API
  2. Register required callbacks
  3. Subscribe with a list of symbols

For History Data:

  1. Initialize the API
  2. Make asynchronous calls to the respective methods exposed

Note: A working sample is available at the bottom of this documentation.


Importing the Library

Import the necessary modules in your Python script:

  1. import asyncio from pix_apidata import *

Initialization

Initialize the API with your credentials:

  1. api = apidata_lib.ApiData() event_loop = asyncio.get_event_loop() apiKey = "api-access-key" # Provided by your data vendor apiHost = "apidata.accelpix.in" # Provided by your data vendor await api.initialize(apiKey, apiHost) # *** IMPORTANT *** # Ensure that you wait for the `initialize(...)` method to complete before making any other API calls.

Symbol Master

Use the following REST API to retrieve master data. This endpoint is specifically for master data downloads due to the larger data size.

API Endpoint

  1. https://apidata.accelpix.in/api/hsd/Masters/2?fmt=json

Sample Response

  1. { "xid": 1, "tkr": "20MICRONS", "atkr": null, "ctkr": null, "exp": "1970-01-01 00:00:00", "utkr": null, "inst": "EQUITY", "a3tkr": null, "sp": 0.00, "tk": 16921 }

Callbacks for Live Streaming

The AccelPix Data API provides various callbacks to handle live streaming data effectively.

Trade Callback

api.on_trade_update(on_trade)

  1. # Callback to listen for trade data api.on_trade_update(on_trade) def on_trade(msg): print(msg) # Trade message t = apidata_models.Trade(msg) print(t.ticker, t.oi) # Access object attributes like id, kind, ticker, segment, price, qty, volume, oi
Sample Response
  1. { "id": 0, "ticker": "NIFTY-1", "segmentId": 2, "time": 1293704493, "price": 13958.6, "qty": 75, "volume": 1587975, "oi": 9700275, "kind": "T" }

Trade Snapshot Callback

api.on_tradeSnapshot_update(on_tradeSnapshot)

  1. # Callback to listen for trade snapshots, called during the subscription process # Listen to `on_trade_update` callback for continuous stream data api.on_tradeSnapshot_update(on_tradeSnapshot) def on_tradeSnapshot(msg): print(msg) # TradeSnapshot message t = apidata_models.Trade(msg) print(t.ticker, t.oi) # Access object attributes like id, kind, ticker, segment, price, qty, volume, oi
Sample Response
  1. { "id": 0, "ticker": "NIFTY-1", "segmentId": 2, "time": 1293704493, "price": 13958.6, "qty": 75, "volume": 1587975, "oi": 9700275, "kind": "T" }

Best Callback

api.on_best_update(on_best)

  1. # Callback to listen for bid, ask, and respective quantities api.on_best_update(on_best) def on_best(msg): print(msg) # Best message b = apidata_models.Best(msg) print(b.ticker, b.bidPrice) # Access object attributes like segmentId, kind, bidQty, askPrice, askQty
Sample Response
  1. { "ticker": "NIFTY-1", "segmentId": 2, "kind": "B", "bidPrice": 13957.45, "bidQty": 75, "askPrice": 13958.8, "askQty": 75, "time": 1293704493 }

Refs Callback

api.on_refs_update(on_ref)

  1. # Callback to listen for changes in open, high, low, close, open interest, and average data api.on_refs_update(on_ref) def on_ref(msg): print(msg) # Refs message ref = apidata_models.Refs(msg) print(ref.price) # Access object attributes like segmentId, kind, ticker
Sample Response
  1. { "kind": "A", "ticker": "NIFTY-1", "segmentId": 2, "price": 11781.08984375 }

Refs Snapshot Callback

api.on_srefs_update(on_srefs)

  1. # Callback to listen for snapshots of open, high, low, close, open interest, average, and band data api.on_srefs_update(on_srefs) def on_srefs(msg): print(msg) # Refs snapshot message sref = apidata_models.RefsSnapshot(msg) print(sref.high) # Access object attributes like kind, ticker, segmentId, open, close, high, low, avg, oi, upperBand, lowerBand
Sample Response
  1. { "kind": "V", "ticker": "NIFTY-1", "segmentId": 2, "open": 11749.650390625, "close": 11681.5498046875, "avg": 11780.8603515625, "high": 11822, "low": 11731.2001953125, "oi": 10615950, "upperBand": 0, "lowerBand": 0 }

Option Greeks Callback

api.on_greeks_update(on_greeks)

  1. # Callback to listen for Option Greeks data api.on_greeks_update(on_greeks) def on_greeks(msg): print(msg) # Option Greeks Data greeks = apidata_models.Greeks(msg) print(greeks.gamma) # Access object attributes like kind, ticker, iv, delta, theta, vega, gamma, ivvwap, vanna, charm, speed, zomma, color, volga, veta, tgr, tv, dtr
Sample Response
  1. { "kind": "G", "ticker": "NIFTY2220318500CE", "charm": 13.510149002075195, "color": 0.0010876863962039351, "ivvwap": 0.2657951712608337, "speed": -0.25761404633522034, "tgr": 1437.1766357421875, "theta": -3.690974235534668, "tv": -28860.783203125, "vega": 1.935671329498291, "veta": 57653.11328125, "volga": 0.000020740208128700033, "zomma": 3.531916377141897e-7, "iv": 0.2650300860404968, "gamma": 0.00012788892490789294, "dtr": -1.9068187475204468, "delta": 0.03707314282655716 }

Option Greeks Snapshot Callback

api.on_greeks_update(on_greekSnapshot)

  1. # Callback to listen for Option Greeks snapshot data api.on_greeks_update(on_greekSnapshot) def on_greekSnapshot(msg): print(msg) # Option Greeks snapshot message greeks = apidata_models.Greeks(msg) print(greeks.gamma) # Access object attributes like kind, ticker, iv, delta, theta, vega, gamma, ivvwap, vanna, charm, speed, zomma, color, volga, veta, tgr, tv, dtr
Sample Response
  1. { "kind": "G", "ticker": "NIFTY2220318500CE", "charm": 13.510149002075195, "color": 0.0010876863962039351, "ivvwap": 0.2657951712608337, "speed": -0.25761404633522034, "tgr": 1437.1766357421875, "theta": -3.690974235534668, "tv": -28860.783203125, "vega": 1.935671329498291, "veta": 57653.11328125, "volga": 0.000020740208128700033, "zomma": 3.531916377141897e-7, "iv": 0.2650300860404968, "gamma": 0.00012788892490789294, "dtr": -1.9068187475204468, "delta": 0.03707314282655716 }

Callbacks for Connection Status

Monitor the connection status using the following callbacks:

Connection Started Callback

api.on_connection_started(connection_started)

  1. # Fired when the connection is successfully established def connection_started(): print("Connection started callback")

Connection Stopped Callback

api.on_connection_stopped(connection_stopped)

  1. # Fired when the connection is closed after an automatic retry or due to networking issues # You need to re-establish the connection manually def connection_stopped(): print("Connection stopped callback")

Live Stream Subscription

Subscribe to various live data streams based on your requirements.

Subscribe to Receive Updates of Segments Entitled to You

  1. needSnapshot = False await api.subscribeSegments(needSnapshot) # IMPORTANT NOTE: # If `needSnapshot = True`, buffer the updates received on `api.on_tradeSnapshot_update` and `api.on_srefs_update` before processing. # Data transfer is substantial and you may get disconnected from the server if you don't process incoming updates quickly enough. # It's advised to buffer the data and then process it once the `api.subscribeSegments` method returns.

Subscribe to Receive All Updates

  1. await api.subscribeAll(['NIFTY-1'])

Subscribe to Receive Trade Updates

  1. await api.subscribeTrade(['NIFTY-1', 'BANKNIFTY-1', 'NIFTY 50'])

Subscribe to Receive Refs and Best Updates

  1. await api.subscribeBestAndRefs(['NIFTY-1', 'BANKNIFTY-1'])

Subscribe to Receive Greeks Updates

  1. await api.subscribeGreeks(['NIFTY2220318500CE'])

Subscribe to Receive Option Chain Updates

  1. # Parameters: spotName, Expiry Date # Subscribe to full option chain await api.subscribeOptionChain('BANKNIFTY', '20220901') # Subscribe to a range of strikes (CE, PE) considering the current spot value at the time of subscription as the mid-point. # This subscribes to 10 strikes (CE, PE) below and 10 strikes (CE, PE) above the mid-point, totaling 40 contracts. await api.subscribeOptionChainRange('NIFTY', '20220901', 10)

Unsubscribe Live Stream

Unsubscribe Single Symbol

  1. await api.unsubscribeAll(['NIFTY-1'])

Unsubscribe Multiple Symbols

  1. await api.unsubscribeAll(['NIFTY-1', 'BANKNIFTY-1'])

Unsubscribe Option Chain Updates

  1. await api.unsubscribeOptionChain('NIFTY', '20220609')

Unsubscribe Greeks Updates

  1. await api.unsubscribeGreeks(['NIFTY2220318500CE'])

History Data

Access historical market data using the following methods.

End of Day (EOD)

Retrieve EOD data for specified tickers and date ranges.

  1. # Continuous data # Parameters: ticker, startDate, endDate await api.get_eod("NIFTY-1", "20200828", "20200901") # Contract data # Parameters: underlying ticker, startDate, endDate, contractExpiryDate await api.get_eod_contract("NIFTY", "20200828", "20200901", "20201029")
Sample Response
  1. { "td": "2020-08-28T00:00:00", "op": 11630, "hp": 11708, "lp": 11617.05, "cp": 11689.05, "vol": 260625, "oi": 488325 }

Intra-Day

Retrieve intra-day data with minute-level resolution.

Features:

  • Provides intra-EOD bars with time resolution in minutes (default: 5 minutes).
  • Supports resolutions of 1, 5, 10 minutes, and custom resolutions like 3, 7 minutes.
  • Passing the current date as a parameter in toDate returns live tick aggregation up to the time traded today. The last bar of the current day may be incomplete. Current day tick aggregation response always provides a complete list of bars from the beginning of the day.
  1. # Continuous data # Parameters: ticker, startDate, endDate, resolution await api.get_intra_eod("NIFTY-1", "20210603", "20210604", "5") # Contract data # Parameters: underlying ticker, startDate, endDate, contractExpiryDate, resolution await api.get_intra_eod_contract("NIFTY", "20200828", "20200901", "20201029", "5")
Sample Response
  1. { "td": "2020-08-28T09:15:00", "op": 11630, "hp": 11643.45, "lp": 11630, "cp": 11639.8, "vol": 4575, "oi": 440475 }

Ticks

Retrieve tick data from a specified date and time up to the current live time.

  1. # Parameters: ticker, fromDateTime await api.get_back_ticks("BANKNIFTY-1", "20201016 15:00:00")
Sample Response
  1. { "td": "2020-11-16T15:00:01.000Z", "pr": 23600, "vol": 125, "oi": 1692375 }

Examples

Below is a working example demonstrating how to use the AccelPix Data API to subscribe to live data streams and retrieve historical data.

  1. import asyncio import time # import requests from pix_apidata import * api = apidata_lib.ApiData() event_loop = asyncio.get_event_loop() async def main(): # Register connection status callbacks api.on_connection_started(connection_started) api.on_connection_stopped(connection_stopped) # Register data callbacks api.on_trade_update(on_trade) api.on_best_update(on_best) api.on_refs_update(on_refs) api.on_srefs_update(on_srefs) api.on_tradeSnapshot_update(on_tradeSnapshot) api.on_greeks_update(on_greeks) api.on_greekSnapshot_update(on_greekSnapshot) # Initialize the API key = "your-api-key" host = "apidata.accelpix.in" scheme = "http" s = await api.initialize(key, host, scheme) print(s) # Retrieve intra-day historical data his = await api.get_intra_eod("NIFTY-1", "20210603", "20210604", "5") print("History:", his) # Define symbols and Greeks symbols syms = ['NIFTY-1', 'BANKNIFTY-1'] symsGreeks = ["BANKNIFTY2290126500CE"] # Subscribe to live data streams await api.subscribeAll(syms) # Uncomment the following lines to subscribe to additional streams # await api.subscribeOptionChain('NIFTY', '20220901') # await api.subscribeGreeks(symsGreeks) # await api.subscribeOptionChainRange('NIFTY', '20220901', 3) print("Subscribe Done") # Optionally, unsubscribe after a delay # needSnapshot = False # await api.subscribeSegments(needSnapshot) # time.sleep(5) # await api.unsubscribeAll(['NIFTY-1']) # await api.unsubscribeGreeks(['BANKNIFTY2290126500CE']) # await api.unsubscribeOptionChain('NIFTY', '20220901') def on_trade(msg): trd = apidata_models.Trade(msg) print("Trade:", msg) # Alternatively, access specific attributes like trd.volume def on_best(msg): bst = apidata_models.Best(msg) print("Best:", msg) # Alternatively, access specific attributes like bst.bidPrice def on_refs(msg): ref = apidata_models.Refs(msg) print("Refs snapshot:", msg) # Alternatively, access specific attributes like ref.price def on_srefs(msg): sref = apidata_models.RefsSnapshot(msg) print("Refs update:", msg) # Alternatively, access specific attributes like sref.high def on_tradeSnapshot(msg): trdSnap = apidata_models.Trade(msg) print("TradeSnap:", msg) # Alternatively, access specific attributes like trdSnap.volume def on_greeks(msg): greeks = apidata_models.Greeks(msg) print("OptionGreeks:", msg) # Alternatively, access specific attributes like greeks.gamma def on_greekSnapshot(msg): gr = apidata_models.Greeks(msg) print(msg) # Alternatively, access specific attributes like gr.gamma def connection_started(): print("Connection started callback") def connection_stopped(): print("Connection stopped callback") # Create and run the main task event_loop.create_task(main()) try: event_loop.run_forever() finally: event_loop.close()


    • Related Articles

    • Pix APIs - Realtime and Historical Data in Node.js

      Introduction Pix APIs is a robust JavaScript library designed to connect and stream market data efficiently. Utilizing WebSocket and fallback transport mechanisms, this library provides comprehensive functionalities to access both End of Day (EOD) ...
    • Pix APIs - Realtime and Historical Data in REST

      Introduction ACCELPIX REST API is a robust interface designed for downloading historical and tick data efficiently. Whether you're looking to retrieve End of Day (EOD) data, intra-EOD data, live intra OHLC (Open, High, Low, Close) data, or quotes, ...
    • How to configure Realtime NSE Data in Excel ?

      India's Fastest Realtime (Tick by Tick 1 Sec Updates) Data in MS Excel. The following are the minimum requirements: - 1. Microsoft Office Excel 2010 or above 2. Pix Connect Elite and the Above plans can be used with Excel. How to Setup Pix Connect ...
    • How to download Daily IEOD Incremental Data using Pix Connect ?

      Intraday End of Day Data ( IEOD ) is too crucial for backtesting purposes, that's why we do provide for all our subscribers at FREE OF COST with REALTIME Data Subscription. We are updating these data every day within 25 min after the market close (at ...
    • NinjaTrader 7 Market Profile TPO / Volume Profile Settings using Pix Connect !

      Market Profile TPO is a widely used indicator in NInjaTrader 7 and here will show you the settings which you need to implement in your NinjaTrader 7. Hope you have properly installed our Pix Connect and TA Extention (If not, please install it from ...