WebSockets – Python

Introduction

To connect using WebSockets API, you will need following information :
 
– “endpoint” to connect to,
– “port number” to connect to,
– “API Key”
 
You will get all of the above once you purchase the API from our team
 
The flow of operations should be as follows :
 
1. Make a connection to the ws://endpoint:port
2. Send Authentication Request using API Key
3. Once authentication is successful, send all other data requests
4. If connection is lost for any reasons, follow same steps from 1 to 3 as above.
 
Ready, lets gets started then
 

Download the sample

– Download Python Sample from Download Code Samples page.
– The sample is zipped. Once downloaded, extract it to some folder using WinZip or WinRar
– Open the WebsocketSample_Phython.py in the editor. You can use Visual Studio Code, IDLE or any compatible Editor
 
Note the code below in file at the top :
 

"""
GFDL TODO - please enter below the endpoint received from GFDL team. 
If you dont have one, please contact us on sales@globaldatafeeds.in 
"""  
endpoint = "ws://endpoint:port/"

"""
//GFDL TODO - please enter below the API Key received from GFDL team. 
If you dont have one, please contact us on sales@globaldatafeeds.in 
"""
accesskey = "Enter Your API Key Here"

 
– Enter the Endpoint, Port and API Access Key received from our team in above code.
– Save this file and run it. You can run it directly in the editor (if supported) or you can run it in your browser.
– Make sure you run the sample during market hours.

What happens when sample is run for the first time ?

– When sample is run for the first time, it sends request to server for SubscribeRealtime function (NIFTY-I Symbol from NFO Exchange). SubscribeRealtime pushes realtime data of requested symbol from server to client i.e. to you. If your account is not enabled for this Exchange, kindly make suitable changes in async def SubscribeRealtime() function and replace ExchangeName & InstIdentifier variables. The sample code has examples of symbols from other Exchanges for quick reference. For complete reference, please see Symbol Naming Conventions.
– If you run sample during market hours, you will notice updation of realtime data of available symbols at your end.
– The code below will be run when sample is run :
 

"""
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/* 	GFDL : 	1. 	SubscribeRealtime : pushes realtime data every second for the subscribed instrument from server
				2. 	So you will need to send this request only once and subscribe for the data.	
				3.	Please note that if there is internet disconnection for any reason, you will need to 
					subscribe to all the instruments again - to receive the data.
				4.	To see this function in action, you should run it during market hours
				5.	If you want to subscribe to data of multiple symbols, you will need to send 1 request each - for each symbol
				6. 	Please see symbol naming conventions here : https://globaldatafeeds.in/global-datafeeds-apis/global-datafeeds-apis/documentation-support/symbol-naming-convention/
	*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
"""

"""
    Subscribing to realtime data of Futures & Options :
    ---------------------------------------------------
	//Below request will subscribe to realtime data of Current Month Futures of NIFTY	
	//This example shows how to request data using Continuous Format
	//Similarly, you can send NIFTY-II (Near month), NIFTY-III (Far month). 
	//Below Symbol is Continuous Format of NIFTY Futures. It will never expire. So no change in code will be necessary.
	//You can use same naming convention for Futures of Instruments from NFO, CDS, MCX Exchanges
	//CDS Examples : USDINR-I, USDINR-II, USDINR-III
	//MCX Examples : NATURALGAS-I, NATURALGAS-II, NATURALGAS-III
	
	//Similarly, you can send NIFTY20AUGFUT (near month), NIFTY20SEPFUT (far month). 
	//You can use same naming convention for Futures of Instruments from NFO, CDS, MCX Exchanges
	//NFO Options Examples : NIFTY02JUL2010000CE, RELIANCE30JUL201700CE
	//CDS Futures Examples : USDINR20JULFUT, USDINR20AUGFUT, USDINR20SEPFUT
	//CDS Options Examples : USDINR29JUL2075.5CE, EURINR29JUL2080CE
	//MCX Options Examples : CRUDEOIL20JULFUT, CRUDEOIL20AUGFUT, CRUDEOIL20SEPFUT
	//MCX Options Examples : CRUDEOIL20JUL2050PE, GOLD20JUL43700PE	
	//Important : Replace it with appropriate expiry date if this contract is expired

	//Similarly, you can send FUTIDX_NIFTY_27AUG2020_XX_0 (near month), FUTIDX_NIFTY_24SEP2020_XX_0 (far month). 
	//You can use same naming convention for Futures of Instruments from NFO, CDS, MCX Exchanges
	//NFO Options Examples : OPTIDX_NIFTY_02JUL2020_CE_10000, OPTSTK_RELIANCE_30JUL2020_CE_1700
	//CDS Futures Examples : FUTCUR_USDINR_26JUN2020_XX_0, FUTCUR_USDINR_29JUL2020_XX_0, FUTCUR_USDINR_27AUG2020_XX_0
	//CDS Options Examples : OPTCUR_USDINR_29JUL2020_CE_75.5, OPTCUR_EURINR_29JUL2020_CE_80
	//MCX Futures Examples : FUTCOM_CRUDEOIL_20JUL2020__0, FUTCOM_CRUDEOIL_19AUG2020__0, FUTCOM_CRUDEOIL_21SEP2020__0
	//MCX Options Examples : OPTFUT_CRUDEOIL_16JUL2020_PE_2050, OPTFUT_GOLD_27JUL2020_PE_43700
	//Important : Replace it with appropriate expiry date if this contract is expired

    Subscribing to realtime data of NSE Indices
    -------------------------------------------
	//Use InstrumentIdenfier value "NIFTY 50", "NIFTY BANK", "NIFTY 100", etc.
    //Use NSE_IDX as Exchange
    //Please note that Indices Symbols have white space. For example, between NIFTY & 50, NIFTY & BANK above

    Subscribing to realtime data of NSE Stocks 
    ------------------------------------------
    //For EQ Series, use InstrumentIdentifier value BAJAJ-AUTO, RELIANCE, AXISBANK, LT, etc..
	//To subscribe to realtime data of any other series, append the series name to symbol name 
	//for example, to request data of RELIANCE CAPITAL from BE Series, use RELCAPITAL.BE
	//EQ Series Symbols are mentioned without any suffix

	// Please see symbol naming conventions here : 
	// https://globaldatafeeds.in/global-datafeeds-apis/global-datafeeds-apis/documentation-support/symbol-naming-convention/
"""
async def SubscribeRealtime():
    print("Work in progress...")
    async with websockets.connect(endpoint) as websocket:        
        print("Connecting to endpoint : "+endpoint)        
        strMessage = '{"MessageType":"Authenticate","Password":"' + accesskey + '"}'
        await websocket.send(strMessage)
        print("Sent Authentication Message : "+strMessage)
        response = await websocket.recv()       
        allres = response.split(',')
        strComplete = allres[0].split(':')
        result = strComplete[1]
        while (result != "true"):
            response = await websocket.recv()
            allres = response.split(',')
            strComplete = allres[0].split(':')
            result = strComplete[1]
        if result == "true":
            print("Authentication is Complete!!!")
            ExchangeName = "NFO"        #//GFDL : Supported Values : NFO, NSE, NSE_IDX, CDS, MCX. Mandatory Parameter
            InstIdentifier = "NIFTY-I"
            Unsubscribe = "false"       ##GFDL : To stop data subscription for this symbol, send this value as "true"            
            strMessage = '{"MessageType":"SubscribeRealtime","Exchange":"' + ExchangeName + '","Unsubscribe":"' + Unsubscribe + '","InstrumentIdentifier":"' + InstIdentifier +'"}'
            await websocket.send(strMessage)
            print("Message sent : "+strMessage)
            print("Waiting for response...")
            now = datetime.datetime.now()
            
            #Sample will stop running after 5 mins. To run for more time, modify code below suitably
            stime = now + datetime.timedelta(minutes = 5)
            response = await websocket.recv()
            while (stime >= datetime.datetime.now()):
                response = await websocket.recv()
                print("Response :\n" + response)

Sample Response

Work in progress...
Connecting to endpoint : ENDPOINT_IS_MASKED
Sent Authentication Message : {"MessageType":"Authenticate","Password":"PASSWORD_IS_MASKED"}
Authentication is Complete!!!
Message sent : {"MessageType":"SubscribeRealtime","Exchange":"MCX","Unsubscribe":"false","InstrumentIdentifier":"NATURALGAS-I"}
Waiting for response...
Response :
{"AllowServerOSRunning":false,"MessageType":"AllowServerOSRunningResult"}
Response :
{"Exchange":"MCX","InstrumentIdentifier":"NATURALGAS-I","LastTradeTime":1594040012,"ServerTime":1594040013,"AverageTradedPrice":136.41,"BuyPrice":134.9,"BuyQty":176,"Close":132.1,"High":139.6,"Low":132.0,"LastTradePrice":134.9,"LastTradeQty":1,"Open":132.4,"OpenInterest":17040,"QuotationLot":1250.0,"SellPrice":135.0,"SellQty":125,"TotalQtyTraded":138856,"Value":23677300750.0,"PreOpen":false,"PriceChange":2.8,"PriceChangePercentage":2.12,"OpenInterestChange":4309,"MessageType":"RealtimeResult"}
Response :
{"Exchange":"MCX","InstrumentIdentifier":"NATURALGAS-I","LastTradeTime":1594040012,"ServerTime":1594040014,"AverageTradedPrice":136.41,"BuyPrice":134.9,"BuyQty":176,"Close":132.1,"High":139.6,"Low":132.0,"LastTradePrice":134.9,"LastTradeQty":0,"Open":132.4,"OpenInterest":17040,"QuotationLot":1250.0,"SellPrice":135.0,"SellQty":128,"TotalQtyTraded":138856,"Value":23677300750.0,"PreOpen":false,"PriceChange":2.8,"PriceChangePercentage":2.12,"OpenInterestChange":4309,"MessageType":"RealtimeResult"}
Response :
{"Exchange":"MCX","InstrumentIdentifier":"NATURALGAS-I","LastTradeTime":1594040015,"ServerTime":1594040015,"AverageTradedPrice":136.41,"BuyPrice":134.9,"BuyQty":173,"Close":132.1,"High":139.6,"Low":132.0,"LastTradePrice":134.9,"LastTradeQty":4,"Open":132.4,"OpenInterest":17043,"QuotationLot":1250.0,"SellPrice":135.0,"SellQty":129,"TotalQtyTraded":138860,"Value":23677975375.0,"PreOpen":false,"PriceChange":2.8,"PriceChangePercentage":2.12,"OpenInterestChange":4312,"MessageType":"RealtimeResult"}
Response :
{"MessageType":"Echo"}
Response :
{"Exchange":"MCX","InstrumentIdentifier":"NATURALGAS-I","LastTradeTime":1594040015,"ServerTime":1594040016,"AverageTradedPrice":136.41,"BuyPrice":134.9,"BuyQty":174,"Close":132.1,"High":139.6,"Low":132.0,"LastTradePrice":134.9,"LastTradeQty":2,"Open":132.4,"OpenInterest":17044,"QuotationLot":1250.0,"SellPrice":135.0,"SellQty":130,"TotalQtyTraded":138862,"Value":23678312625.0,"PreOpen":false,"PriceChange":2.8,"PriceChangePercentage":2.12,"OpenInterestChange":4313,"MessageType":"RealtimeResult"}
Response :
{"Exchange":"MCX","InstrumentIdentifier":"NATURALGAS-I","LastTradeTime":1594040016,"ServerTime":1594040017,"AverageTradedPrice":136.41,"BuyPrice":134.9,"BuyQty":173,"Close":132.1,"High":139.6,"Low":132.0,"LastTradePrice":134.9,"LastTradeQty":1,"Open":132.4,"OpenInterest":17045,"QuotationLot":1250.0,"SellPrice":135.0,"SellQty":133,"TotalQtyTraded":138863,"Value":23678481250.0,"PreOpen":false,"PriceChange":2.8,"PriceChangePercentage":2.12,"OpenInterestChange":4314,"MessageType":"RealtimeResult"}
Response :
{"MessageType":"Echo"}
Response :
{"Exchange":"MCX","InstrumentIdentifier":"NATURALGAS-I","LastTradeTime":1594040017,"ServerTime":1594040017,"AverageTradedPrice":136.41,"BuyPrice":134.9,"BuyQty":174,"Close":132.1,"High":139.6,"Low":132.0,"LastTradePrice":134.9,"LastTradeQty":1,"Open":132.4,"OpenInterest":17044,"QuotationLot":1250.0,"SellPrice":135.0,"SellQty":141,"TotalQtyTraded":138864,"Value":23678649875.0,"PreOpen":false,"PriceChange":2.8,"PriceChangePercentage":2.12,"OpenInterestChange":4313,"MessageType":"RealtimeResult"}
Response :
{"Exchange":"MCX","InstrumentIdentifier":"NATURALGAS-I","LastTradeTime":1594040018,"ServerTime":1594040018,"AverageTradedPrice":136.41,"BuyPrice":134.9,"BuyQty":172,"Close":132.1,"High":139.6,"Low":132.0,"LastTradePrice":135.0,"LastTradeQty":5,"Open":132.4,"OpenInterest":17044,"QuotationLot":1250.0,"SellPrice":135.0,"SellQty":142,"TotalQtyTraded":138869,"Value":23679493250.0,"PreOpen":false,"PriceChange":2.9,"PriceChangePercentage":2.2,"OpenInterestChange":4313,"MessageType":"RealtimeResult"}

– To know how each function works, you can uncomment required function at top (one function at a time), save the sample and run it.
 

Trouble-shooting

The code outputs nothing

– Please make sure you have entered the Endpoint, Port & API Key in the sample code, saved the changes before running it.
– To see realtime data in action, you should run the sample during market hours
– If you are behind firewall, please speak to your network administrator and get the endpoint URL and port whitelisted in your firewall
 

I can see some output but I dont see all symbols requested / I get “Exchange Not Enabled.” message

– SubscribeRealtime function requests data of a symbol (NIFTY-I from NFO Exchange in the unedited sample). You will need to make sure you have paid for the subscription of the Exchange you are using in your request.
 
– Some examples use Contractwise symbols which might have expired. Please check code and change the symbols. Please check Symbol Naming Conventions page for more information about various ways to name symbols (especially Futures and Options).
 

I have requested data but it takes lot of time to receive the response

– If you have requested entire GetHistory, GetInstruments (for NSE / NFO), GetExchangeSnapshot or GetLastQuoteOptionChain, these functions return thousands of rows. So it is possible that it takes more time than other requests to return the data
 
– Please make sure you are on fast internet connection.
 

I have other issues not listed here

– Please drop an email to developer@globaldatafeeds.in with following :
1. Details of the request sent (exact syntax), expected response & received response
2. Screenshot of the request & response
3. API Key used
 
Once received, we will check and revert at the earliest (typically within few hours for normal queries).

Was this helpful?