API Reference

Submodules

integrate.connect module

This module contains the ConnectToIntegrate class which is used to connect to the Integrate API and login, get symbols and send requests.

Example:

from integrate import ConnectToIntegrate

# Create a ConnectToIntegrate object
c2i = ConnectToIntegrate()

# Login to Integrate
c2i.login(api_token="YOUR_API_TOKEN", api_secret="YOUR_API_SECRET")

# Get symbols
for symbol in c2i.symbols:
    print(symbol)
class integrate.connect.ConnectToIntegrate(login_url: str | None = None, base_url: str | None = None, timeout: int | None = None, logging: bool = False, proxies: dict[str, str] | None = None, ssl_verify: bool = True)

Bases: object

Definedge Securities Integrate Connection API class

Parameters:
  • login_url (str | None) – URL to use for login

  • base_url (str | None) – Base URL to use for API requests

  • timeout (int | None) – Maximum time (seconds) for which the API client will wait for a request to complete before it fails. Defaults to 10 seconds.

  • logging (bool) – Enable or disable logging. Defaults to False. If set to True, will print all requests and responses to logger.

  • proxies (dict[str, str] | None) – To set requests proxy. Required when the client’s requests are going through a proxy server. Check requests documentation for usage and examples.

EXCHANGE_TYPE_BFO = 'BFO'
EXCHANGE_TYPE_BSE = 'BSE'
EXCHANGE_TYPE_CDS = 'CDS'
EXCHANGE_TYPE_MCX = 'MCX'
EXCHANGE_TYPE_NFO = 'NFO'
EXCHANGE_TYPE_NSE = 'NSE'
GTT_CONDITION_LTP_ABOVE = 'LTP_ABOVE'
GTT_CONDITION_LTP_BELOW = 'LTP_BELOW'
ORDER_STATUS_CANCELLED = 'CANCELED'
ORDER_STATUS_COMPLETE = 'COMPLETE'
ORDER_STATUS_NEW = 'NEW'
ORDER_STATUS_OPEN = 'OPEN'
ORDER_STATUS_REJECTED = 'REJECTED'
ORDER_STATUS_REPLACED = 'REPLACED'
ORDER_TYPE_BUY = 'BUY'
ORDER_TYPE_SELL = 'SELL'
PRICE_TYPE_LIMIT = 'LIMIT'
PRICE_TYPE_MARKET = 'MARKET'
PRICE_TYPE_SL_LMT = 'SL-LIMIT'
PRICE_TYPE_SL_MKT = 'SL-MARKET'
PRODUCT_TYPE_CNC = 'CNC'
PRODUCT_TYPE_INTRADAY = 'INTRADAY'
PRODUCT_TYPE_NORMAL = 'NORMAL'
SUBSCRIPTION_TYPE_DEPTH = 'DEPTH'
SUBSCRIPTION_TYPE_ORDER = 'ORDER'
SUBSCRIPTION_TYPE_TICK = 'TICK'
TIMEFRAME_TYPE_DAY = 'day'
TIMEFRAME_TYPE_MIN = 'minute'
TIMEFRAME_TYPE_TICK = 'tick'
VALIDITY_TYPE_DAY = 'DAY'
VALIDITY_TYPE_EOS = 'EOS'
VALIDITY_TYPE_IOC = 'IOC'
get_session_keys() tuple[str, str, str, str]

Get stored session keys

Returns:

The session keys

Return type:

tuple[str, str, str, str]

login(api_token: str, api_secret: str, totp: str | None = None) None

Login to Definedge Securities Integrate

Parameters:
send_request(route_prefix: str, route: str, method: str, url_params: dict[str, str] | None = None, json_params: dict[str, Any] | None = None, data_params: dict[str, Any] | None = None, query_params: dict[str, str] | None = None, extra_headers: dict[str, str] | None = None) dict[str, Any]

Make an HTTP request.

Parameters:
  • route_prefix (str) – The prefix of the route

  • route (str) – The route

  • method (str) – The HTTP method

  • url_params (dict) – The URL parameters

  • json_params (dict) – The JSON parameters

  • data_params (dict) – The data parameters

  • query_params (dict) – The query parameters

  • extra_headers (dict) – The extra headers

Returns:

The response

Return type:

dict

set_session_keys(uid: str, actid: str, api_session_key: str, ws_session_key: str) None

Store session keys

Parameters:
  • uid (str) – Your Definedge Securities login UCC id

  • actid (str) – Your Definedge Securities login account id

  • api_session_key (str) – Your Definedge Securities API session key

  • ws_session_key (str) – Your Definedge Securities WebSocket session key

property symbols: Generator[dict[str, str], None, None]

Download the master file for symbols and create a generator

Returns:

A generator of symbols

Return type:

Generator[dict[str, str], None, None]

integrate.data module

This module contains the IntegrateData class which is used to connect to the Integrate Data API and fetch historical data, quotes and security information.

Example:

from datetime import datetime

from integrate import ConnectToIntegrate, IntegrateData

c2i = ConnectToIntegrate()
c2i.login(api_token="YOUR_API_TOKEN", api_secret="YOUR_API_SECRET")

ic = IntegrateData(connect_to_integrate=c2i)

# Fetch historical data for a symbol
historical_data = ic.historical_data(
    exchange=c2i.EXCHANGE_TYPE_NSE,
    trading_symbol="ACC-EQ",
    timeframe=c2i.TIMEFRAME_TYPE_DAY,
    start=datetime.strptime("300620230915", "%d%m%Y%H%M"),
    end=datetime.strptime("300620231530", "%d%m%Y%H%M"),
)

# Fetch quotes for a symbol
quotes = ic.quotes(
    exchange=c2i.EXCHANGE_TYPE_NSE,
    trading_symbol="ACC-EQ",
)

# Fetch security information for a symbol
security_information = ic.security_information(
    exchange=c2i.EXCHANGE_TYPE_NSE,
    trading_symbol="ACC-EQ",
)
class integrate.data.IntegrateData(connect_to_integrate: ConnectToIntegrate, logging: bool = False)

Bases: object

Definedge Securities Integrate Data API class

Parameters:
  • connect_to_integrate (ConnectToIntegrate) – The connection object.

  • logging (bool) – Enable or disable logging. Defaults to False. If set to True, will print all requests and responses to logger.

historical_data(exchange: str, trading_symbol: str, timeframe: str, start: datetime, end: datetime) Generator[dict[str, Any], None, None]

Retrieve historical data for an security.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • trading_symbol (str) – Trading symbol of the security.

  • timeframe (str) – Timeframe of the data. day or minute are supported.

  • start (datetime) – Start date of the data.

  • end (datetime) – End date of the data.

Returns:

Historical data for the security.

Return type:

Generator[dict[str, Any], None, None]

quotes(exchange: str, trading_symbol: str) dict[str, Any]

Retrieve quotes for an security.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • trading_symbol (str) – Trading symbol of the security.

Returns:

Quote for the security.

Return type:

dict[str, Any]

security_information(exchange: str, trading_symbol: str) dict[str, Any]

Retrieve details about an security.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • trading_symbol (str) – Trading symbol of the security.

Returns:

Details about the security.

Return type:

dict[str, Any]

integrate.orders module

This module contains the IntegrateOrders class which is used to connect to the Integrate Orders API and place orders, modify orders, cancel orders, get order book, get order status, get trade book, get positions, convert product type, place GTT order, modify GTT order, cancel GTT order.

Example:

from integrate import ConnectToIntegrate, IntegrateOrders

c2i = ConnectToIntegrate()
c2i.login(api_token="YOUR_API_TOKEN", api_secret="YOUR_API_SECRET")

io = IntegrateOrders(c2i)
io.place_order(
     exchange="NSE",
     order_type="BUY",
     price=0,
     price_type="MARKET",
     product_type="INTRADAY",
     quantity=1,
     tradingsymbol="ACC-EQ",
)
io.order(order_id="210630000000000")
io.orders()
class integrate.orders.IntegrateOrders(connect_to_integrate: ConnectToIntegrate, logging: bool = False)

Bases: object

Definedge Securities Integrate Orders API class

Parameters:
  • connect_to_integrate (ConnectToIntegrate) – The connection object.

  • logging (bool) – Enable or disable logging. Defaults to False. If set to True, will print all requests and responses to logger.

cancel_gtt_order(alert_id: str) dict[str, Any]

Cancel a GTT order.

Parameters:

alert_id (str) – Alert id of the GTT order.

Returns:

Cancellation response details

Return type:

dict[str, Any]

cancel_oco_order(alert_id: str) dict[str, Any]

Cancel a OCO order.

Parameters:

alert_id (str) – Alert id of the OCO order.

Returns:

Cancellation response details

Return type:

dict[str, Any]

cancel_order(order_id: str) dict[str, Any]

Cancel an order.

Parameters:

order_id (str) – Order ID of the order to be cancelled.

Returns:

Cancellation response details

Return type:

dict[str, Any]

convert_position_product_type(exchange: str, order_type: str, previous_product: str, product_type: str, quantity: int, tradingsymbol: str, position_type: str = 'DAY') dict[str, Any]

Convert an open position’s product type.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • order_type (str) – Order type. Valid values are BUY, SELL.

  • previous_product (str) – Previous product type. Valid values are CNC, INTRADAY, NORMAL.

  • product_type (str) – Product type. Valid values are CNC, INTRADAY, NORMAL.

  • quantity (int) – Quantity to transact.

  • tradingsymbol (str) – Trading symbol of security to transact.

  • position_type (str) – Position type. Valid values are DAY, IOC, EOS.

Returns:

The order details

Return type:

dict[str, Any]

gtt_orders() dict[str, Any]

Get list of GTT orders.

Returns:

List of GTT orders.

Return type:

dict[str, Any]

holdings() dict[str, Any]

Retrieve the list of holdings.

Returns:

List of holdings.

Return type:

dict[str, Any]

limits() dict[str, Any]

Get account balance and cash margin details for all segments.

Returns:

Account balance and cash margin details for all segments.

Return type:

dict[str, Any]

margins(orders: list[dict[str, Any]]) dict[str, Any]

Get margin for a list of orders.

Parameters:

orders (list[dict[str, str]]) – List of orders.

Returns:

Margin for a list of orders.

Return type:

dict[str, Any]

modify_gtt_order(exchange: str, alert_id: str, order_type: str, price: float, quantity: int, tradingsymbol: str, alert_price: float, condition: str) dict[str, Any]

Modify a GTT order.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • alert_id (str) – Alert id of the GTT order.

  • order_type (str) – Order type. Valid values are BUY, SELL.

  • price (float) – Price at which order is to be placed.

  • quantity (int) – Quantity to transact.

  • tradingsymbol (str) – Trading symbol of security to transact.

  • alert_price (float) – Price at which alert is to be triggered.

  • condition (str) – Condition to be met. Valid values are LTP_BELOW, LTP_ABOVE.

Returns:

The order details

Return type:

dict[str, Any]

modify_oco_order(exchange: str, alert_id: str, order_type: str, tradingsymbol: str, stoploss_quantity: int, stoploss_price: float, target_quantity: int, target_price: float, remarks: str | None = None) dict[str, Any]

Modify an OCO order.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • alert_id (str) – Alert id of the OCO order.

  • order_type (str) – Order type. Valid values are BUY, SELL.

  • tradingsymbol (str) – Trading symbol of security to transact.

  • stoploss_quantity (int) – Quantity of stoploss order.

  • stoploss_price (float) – Price of stoploss order.

  • target_quantity (int) – Quantity of target order.

  • target_price (float) – Price of target order.

  • remarks (Union[str, None]) – Remarks if any.

Returns:

The order details

Return type:

dict[str, Any]

modify_order(exchange: str, order_id: str, order_type: str, price: float, price_type: str, product_type: str, quantity: int, tradingsymbol: str, amo: str | None = None, book_loss_price: float | None = None, book_profit_price: float | None = None, disclosed_quantity: int | None = None, market_protection: float | None = None, remarks: str | None = None, trailing_price: float | None = None, trigger_price: float | None = None, validity: str = 'DAY') dict[str, Any]

Modify an open order.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • order_id (str) – Order ID of the order to be modified.

  • order_type (str) – Order type. Valid values are BUY, SELL.

  • price (float) – Price at which order is to be placed. Should be 0 for MARKET order.

  • price_type (str) – Price type. Valid values are MARKET, LIMIT, SL-MARKET, SL-LIMIT.

  • product_type (str) – Product type. Valid values are CNC, INTRADAY, NORMAL.

  • quantity (int) – Quantity to transact.

  • tradingsymbol (str) – Trading symbol of security to transact.

  • amo (str) – If set to True, AMO order will be placed. Defaults to False.

  • book_loss_price (float) – Book loss price (Applicable only for Bracket orders).

  • book_profit_price (float) – Book profit price (Applicable only for Bracket orders).

  • disclosed_quantity (int) – Disclosed quantity for the order (Only for Equity and MCX).

  • market_protection (float) – Market protection percentage for the order (only for BSE and MCX).

  • remarks (str) – Remarks for the order.

  • trailing_price (float) – Trailing price for the order (Applicable only High Leverage product and Bracket order).

  • trigger_price (float) – Trigger price for the order (Applicable only for price_type, SL-MARKET or SL-LIMIT).

  • validity (str) – Validity for the order. Valid values are DAY, IOC, EOS. Defaults to DAY.

Returns:

The order details

Return type:

dict[str, Any]

order(order_id: str) dict[str, Any]

Get status of a order.

Returns:

Order status.

Return type:

dict[str, Any]

orders() dict[str, Any]

Get list of orders.

Returns:

List of orders.

Return type:

dict[str, Any]

place_gtt_order(exchange: str, order_type: str, price: float, quantity: int, tradingsymbol: str, alert_price: float, condition: str) dict[str, Any]

Place a GTT order.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • order_type (str) – Order type. Valid values are BUY, SELL.

  • price (float) – Price at which order is to be placed.

  • quantity (int) – Quantity to transact.

  • tradingsymbol (str) – Trading symbol of security to transact.

  • alert_price (float) – Price at which alert is to be triggered.

  • condition (str) – Condition to be met. Valid values are LTP_BELOW, LTP_ABOVE.

Returns:

The order details

Return type:

dict[str, Any]

place_oco_order(exchange: str, order_type: str, tradingsymbol: str, stoploss_quantity: int, stoploss_price: float, target_quantity: int, target_price: float, remarks: str | None = None) dict[str, Any]

Place an OCO order.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • order_type (str) – Order type. Valid values are BUY, SELL.

  • tradingsymbol (str) – Trading symbol of security to transact.

  • stoploss_quantity (int) – Quantity of stoploss order.

  • stoploss_price (float) – Price of stoploss order.

  • target_quantity (int) – Quantity of target order.

  • target_price (float) – Price of target order.

  • remarks (Union[str, None]) – Remarks if any.

Returns:

The order details

Return type:

dict[str, Any]

place_order(exchange: str, order_type: str, price: float, price_type: str, product_type: str, quantity: int, tradingsymbol: str, algo_id: str, amo: str | None = None, book_loss_price: float | None = None, book_profit_price: float | None = None, disclosed_quantity: int | None = None, market_protection: float | None = None, remarks: str | None = None, trailing_price: float | None = None, trigger_price: float | None = None, validity: str = 'DAY') dict[str, Any]

Place an order.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • order_type (str) – Order type. Valid values are BUY, SELL.

  • price (float) – Price at which order is to be placed. Should be 0 for MARKET order.

  • price_type (str) – Price type. Valid values are MARKET, LIMIT, SL-MARKET, SL-LIMIT.

  • product_type (str) – Product type. Valid values are CNC, INTRADAY, NORMAL.

  • quantity (int) – Quantity to transact.

  • tradingsymbol (str) – Trading symbol of security to transact.

  • algo_id – Algo Id for the order.

  • amo – If set to True, AMO order will be placed. Defaults to False.

  • book_loss_price – Book loss price (Applicable only for Bracket orders).

  • book_profit_price – Book profit price (Applicable only for Bracket orders).

  • disclosed_quantity – Disclosed quantity for the order (Only for Equity and MCX).

  • market_protection – Market protection percentage for the order (only for BSE and MCX).

  • remarks – Remarks for the order.

  • trailing_price – Trailing price for the order (Applicable only High Leverage product and Bracket order).

  • trigger_price – Trigger price for the order (Applicable only for price_type, SL-MARKET or SL-LIMIT).

  • validity – Validity for the order. Valid values are DAY, IOC, EOS. Defaults to DAY.

:type algo_id:str :type amo: str :type book_loss_price: float :type book_profit_price: float :type disclosed_quantity: int :type market_protection: float :type remarks: str :type trailing_price: float :type trigger_price: float :type validity: str :return: The order details :rtype: dict[str, Any]

positions() dict[str, Any]

Retrieve the list of positions.

Returns:

List of positions.

Return type:

dict[str, Any]

slice_order(exchange: str, order_type: str, price: float, price_type: str, product_type: str, quantity: int, slices: int, tradingsymbol: str, amo: str | None = None, book_loss_price: float | None = None, book_profit_price: float | None = None, disclosed_quantity: int | None = None, market_protection: float | None = None, remarks: str | None = None, trailing_price: float | None = None, trigger_price: float | None = None, validity: str = 'DAY') dict[str, Any]

Slice an order.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • order_type (str) – Order type. Valid values are BUY, SELL.

  • price (float) – Price at which order is to be placed. Should be 0 for MARKET order.

  • price_type (str) – Price type. Valid values are MARKET, LIMIT, SL-MARKET, SL-LIMIT.

  • product_type (str) – Product type. Valid values are CNC, INTRADAY, NORMAL.

  • quantity (int) – Quantity to transact.

  • slices (int) – Number of slices.

  • tradingsymbol (str) – Trading symbol of security to transact.

  • amo (str) – If set to True, AMO order will be placed. Defaults to False.

  • book_loss_price (float) – Book loss price (Applicable only for Bracket orders).

  • book_profit_price (float) – Book profit price (Applicable only for Bracket orders).

  • disclosed_quantity (int) – Disclosed quantity for the order (Only for Equity and MCX).

  • market_protection (float) – Market protection percentage for the order (only for BSE and MCX).

  • remarks (str) – Remarks for the order.

  • trailing_price (float) – Trailing price for the order (Applicable only High Leverage product and Bracket order).

  • trigger_price (float) – Trigger price for the order (Applicable only for price_type, SL-MARKET or SL-LIMIT).

  • validity (str) – Validity for the order. Valid values are DAY, IOC, EOS. Defaults to DAY.

Returns:

The order details

Return type:

dict[str, Any]

span_calculator(positions: list[dict[str, Any]]) dict[str, Any]

Get span information for a list of positions.

Parameters:

positions (list[dict[str, str]]) – List of positions.

Returns:

Span information for a list of positions.

Return type:

dict[str, Any]

trades() dict[str, Any]

Retrieve the list of trades executed.

Returns:

List of trades executed.

Return type:

dict[str, Any]

integrate.ws module

This module contains the IntegrateWebSocket class which is used to connect to the Integrate WebSocket API and subscribe to ticks, order updates and bid-ask depth updates.

Example:

from integrate import ConnectToIntegrate, IntegrateWebSocket

# Create a ConnectToIntegrate object
c2i = ConnectToIntegrate()

# Login to Integrate
c2i.login(api_token="YOUR_API_TOKEN", api_secret="YOUR_API_SECRET")

# Create an IntegrateWebSocket object
iws = IntegrateWebSocket(c2i)

# Connect to Integrate WebSocket server
iws.connect()

# Check if WebSocket connection is established
iws.is_connected()

# Subscribe to ticks
iws.subscribe(iws.c2i.SUBSCRIPTION_TYPE_TICK)

# Subscribe to order updates
iws.subscribe(iws.c2i.SUBSCRIPTION_TYPE_ORDER)

# Subscribe to bid-ask depth updates
iws.subscribe(iws.c2i.SUBSCRIPTION_TYPE_DEPTH)

# Unsubscribe from ticks
iws.unsubscribe(iws.c2i.SUBSCRIPTION_TYPE_TICK)

# Unsubscribe from order updates
iws.unsubscribe(iws.c2i.SUBSCRIPTION_TYPE_ORDER)

# Unsubscribe from bid-ask depth updates
iws.unsubscribe(iws.c2i.SUBSCRIPTION_TYPE_DEPTH)

# Resubscribe to all current subscribed tokens
iws.resubscribe()

# Stop reconnecting
iws.stop_retry()

# Stop the event loop
iws.stop()
class integrate.ws.IntegrateWebSocket(connect_to_integrate: ConnectToIntegrate, logging: bool = False)

Bases: object

WebSocket client for interacting with Definedge Securities’ streaming quotes, order and depth updates.

Parameters:
  • connect_to_integrate (ConnectToIntegrate) – The connection object.

  • logging (bool) – Enable or disable logging. Defaults to False.

Callbacks

check_token_validity(tokens: list[tuple[str, str]]) None

Check if the given list of security tokens are valid.

Parameters:

tokens (list[tuple[str, str]]) – List of security tokens to check.

Returns:

None

close(code: int | None = None, reason: str | None = None) None

Close the WebSocket connection.

Parameters:
  • code (int) – The close code. Defaults to None.

  • reason (str) – The close reason. Defaults to None.

Returns:

None

close_on_exception(reason: str | None = None) None

Close the WebSocket connection on exception.

Parameters:

reason (str) – The close reason. Defaults to None.

Returns:

None

connect(socket_url: str | None = None, daemonize: bool = False, reconnect: bool = True, reconnect_max_tries: int = 30, reconnect_max_delay: int = 60, connect_timeout: int = 30, ssl_verify: bool = True, proxy: dict[str, str] | None = None) None

Establish a websocket connection with Definedge Securities Integrate.

Parameters:
  • socket_url (str) – The websocket URL to connect to. Defaults to wss://trade.definedgesecurities.com/NorenWSTRTP/.

  • daemonize (bool) – Indicates if the client should run a daemon. Defaults to False.

  • reconnect (bool) – Indicates if the client should auto reconnect. Defaults to True.

  • reconnect_max_tries (int) – Maximum number of retries before it stops reconnecting. Defaults to 30.

  • reconnect_max_delay (int) – Maximum delay after which subsequent reconnection delay will become constant. Defaults to 60.

  • connect_timeout (int) – Maximum time (seconds) for which the API client will wait for a request to complete before it fails. Defaults to 30 seconds.

  • ssl_verify (bool) – Enable or disable SSL verification. Defaults to True.

  • proxy (dict[str, str]) – Proxy URL. Defaults to None.

is_connected() bool

Check if WebSocket connection is established.

Returns:

True if connection is established, else False.

login() None

Login to Definedge Securities Integrate.

Returns:

None

on_acknowledgement(iws: IntegrateWebSocket, ack: dict[str, Any]) None

Callback function called when the WebSocket connection receives an acknowledgement.

Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • ack (dict) – The acknowledgement.

Returns:

None

on_close(iws: IntegrateWebSocket, code: int, reason: str) None

Callback function called when the WebSocket connection is closed. To stop reconnection, use stop method as shown in the example below.

def on_close(iws: IntegrateWebSocket, code: int, reason: str) -> None:
    iws.stop() # this will stop reconnection
Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • code (int) – The close code.

  • reason (str) – The close reason.

Returns:

None

Note:

RFC6455 defines the status codes on connection close.

on_connect(iws: IntegrateWebSocket, response: ConnectionResponse) None

Callback function called when the WebSocket connection is established.

Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • response (ConnectionResponse) – The ConnectionResponse instance.

Returns:

None

on_depth_update(iws: IntegrateWebSocket, depth: dict[str, str]) None

Callback function called when the WebSocket connection receives a depth update.

Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • depth (dict) – The depth update.

Returns:

None

on_error(iws: IntegrateWebSocket, code: int, reason: str) None

Callback function called when the WebSocket connection encounters an error.

Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • code (int) – The error code.

  • reason (str) – The error reason.

Returns:

None

Note:

RFC6455 defines the status codes on connection close.

on_exception(iws: IntegrateWebSocket, e: Exception) None

Callback function called when a Python exception occurs.

Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • e (Exception) – The exception.

Returns:

None

on_login(iws: IntegrateWebSocket) None

Callback function called when the WebSocket connection is logged in.

Parameters:

iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

Returns:

None

on_open(iws: IntegrateWebSocket) None

Callback function called when the WebSocket connection is opened.

Parameters:

iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

Returns:

None

on_order_update(iws: IntegrateWebSocket, order: dict[str, str]) None

Callback function called when the WebSocket connection receives an order update.

Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • order (dict) – The order update.

Returns:

None

on_reconnection(iws: IntegrateWebSocket, retries: int) None

Callback function called when the WebSocket connection is reconnected.

Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • retries (int) – The number of retries.

Returns:

None

on_stop_reconnection(iws: IntegrateWebSocket) None

Callback function called when the WebSocket connection stops retrying to reconnect.

Parameters:

iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

Returns:

None

on_tick_update(iws: IntegrateWebSocket, tick: dict[str, str]) None

Callback function called when the WebSocket connection receives a tick update.

Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • tick (dict) – The tick update.

Returns:

None

resubscribe() None

Resubscribe to all current subscribed tokens.

Returns:

None

stop() None

Stop the event loop.

Returns:

None

Note:

Should be used if main thread has to be closed in on_close method. Reconnection cannot happen after this method is used.

stop_retry() None

Stop auto retry when it is in progress.

Returns:

None

subscribe(subscription_type: str, tokens: list[tuple[str, str]] | None = None) None

Subscribe to a list of security tokens.

Parameters:
  • subscription_type (str) – The subscription type. Valid values are TICK, ORDER and DEPTH.

  • tokens (list[tuple[str, str]]) – List of security tokens to subscribe to. Defaults to None.

Returns:

None

unsubscribe(unsubscription_type: str, tokens: list[tuple[str, str]] | None = None) None

Unsubscribe the given list of security tokens.

Parameters:
  • unsubscription_type (str) – The unsubscription type. Valid values are TICK, ORDER and DEPTH.

  • tokens (list[tuple[str, str]]) – List of security tokens to unsubscribe from. Defaults to None.

Returns:

None

class integrate.ws.IntegrateWebSocketClientFactory(*args, **kwargs)

Bases: WebSocketClientFactory, ReconnectingClientFactory

Definedge Securities Integrate autobahn WebSocket client factory to implement auto reconnection.

Parameters:

reconnect (bool) – Flag indicating whether to reconnect on connection lost.

Returns:

None

Auto reconnection is enabled by default and it can be disabled by passing IntegrateWebSocket.reconnect = False in IntegrateWebSocket.connect(). Reconnection cannot happen if the event loop is terminated using IntegrateWebSocket.stop() method inside IntegrateWebSocket.on_close() callback.

Auto reconnection is based on Exponential backoff algorithm in which next retry delay will be increased exponentially. IntegrateWebSocket.reconnect_max_delay and IntegrateWebSocket.reconnect_max_tries params can be used to tweak the algorithm where: - reconnect_max_delay is the maximum delay after which subsequent reconnection delay will become constant and - reconnect_max_tries is maximum number of retries before it quits reconnection.

For example if reconnect_max_delay is 60 seconds and reconnect_max_tries is 30 then the first reconnection delay starts from minimum delay which is 2 seconds and keep increasing up to 60 seconds after which it becomes constant and when reconnection attempt is reached upto 30 then it stops reconnecting.

Reference:

clientConnectionFailed(connector: BaseConnector, reason: Failure) None

Called when a connection has failed to connect.

Parameters:
  • connector (BaseConnector) – The connector that has failed.

  • reason (Failure) – The reason for the failure.

Returns:

None

clientConnectionLost(connector: BaseConnector, reason: Failure) None

Called when an established connection is lost.

Parameters:
  • connector (BaseConnector) – The connector that has lost connection.

  • reason (Failure) – The reason for the lost connection.

Returns:

None

is_reconnection: bool = False
logging: bool = False
on_close(code: int, reason: str) None

Callback stub for IntegrateWebSocket after onClose.

Parameters:
  • code (int) – Close status code.

  • reason (str) – Close reason.

Returns:

None

on_connect(protocol: IntegrateWebSocketClientProtocol, response: ConnectionResponse) None

Callback stub for IntegrateWebSocket after onConnect.

Parameters:
  • protocol (IntegrateWebSocketClientProtocol) – The WebSocket protocol instance.

  • response (ConnectionResponse) – The HTTP response.

Returns:

None

on_error(code: int, reason: str) None

Callback stub for IntegrateWebSocket when an error occurs.

Parameters:
  • code (int) – Close status code.

  • reason (str) – Close reason.

Returns:

None

on_message(payload: bytes, is_binary: bool) None

Callback stub for IntegrateWebSocket after onMessage.

Parameters:
  • payload (bytes) – The WebSocket message payload.

  • is_binary (bool) – Flag indicating whether the payload is binary or not.

Returns:

None

on_open() None

Callback stub for IntegrateWebSocket after onOpen.

Returns:

None

on_reconnection(retries: int) None

Callback stub for IntegrateWebSocket on reconnection.

Parameters:

retries (int) – The number of retries made.

Returns:

None

on_stop_reconnection() None

Callback stub for IntegrateWebSocket if maxRetries have been made.

Returns:

None

protocol

alias of IntegrateWebSocketClientProtocol

startedConnecting(connector: BaseConnector) None

Called when a connection has been started. Stop trying to connect to server if maxRetries have been made.

Parameters:

connector (BaseConnector) – The connector that has started.

Returns:

None

class integrate.ws.IntegrateWebSocketClientProtocol

Bases: WebSocketClientProtocol

Definedge Securities Integrate autobahn WebSocket protocol to specify the behavior of the client.

Reference:

onClose(wasClean: bool, code: int, reason: str) None

Callback fired when the WebSocket connection has been closed.

Parameters:
  • wasClean (bool) – Flag indicating whether the connection was closed cleanly or not.

  • code (int) – Close status code.

  • reason (str) – Close reason.

Returns:

None

Note:

RFC6455 defines the status codes on connection close

onConnect(response: ConnectionResponse) None

Callback fired during WebSocket opening handshake when a client connects to a server.

Parameters:

response (ConnectionResponse) – The connection response.

Returns:

None

onMessage(payload: bytes, isBinary: bool) None

Callback fired when a complete WebSocket message was received.

Parameters:
  • payload (bytes) – The WebSocket message received.

  • isBinary (bool) – Flag indicating whether payload is binary or UTF-8 encoded text.

Returns:

None

onOpen() None

Callback fired when the initial WebSocket opening handshake was completed.

Returns:

None

Module contents

class integrate.ConnectToIntegrate(login_url: str | None = None, base_url: str | None = None, timeout: int | None = None, logging: bool = False, proxies: dict[str, str] | None = None, ssl_verify: bool = True)

Bases: object

Definedge Securities Integrate Connection API class

Parameters:
  • login_url (str | None) – URL to use for login

  • base_url (str | None) – Base URL to use for API requests

  • timeout (int | None) – Maximum time (seconds) for which the API client will wait for a request to complete before it fails. Defaults to 10 seconds.

  • logging (bool) – Enable or disable logging. Defaults to False. If set to True, will print all requests and responses to logger.

  • proxies (dict[str, str] | None) –

    To set requests proxy. Required when the client’s requests are going through a proxy server. Check requests documentation for usage and examples.

EXCHANGE_TYPE_BFO = 'BFO'
EXCHANGE_TYPE_BSE = 'BSE'
EXCHANGE_TYPE_CDS = 'CDS'
EXCHANGE_TYPE_MCX = 'MCX'
EXCHANGE_TYPE_NFO = 'NFO'
EXCHANGE_TYPE_NSE = 'NSE'
GTT_CONDITION_LTP_ABOVE = 'LTP_ABOVE'
GTT_CONDITION_LTP_BELOW = 'LTP_BELOW'
ORDER_STATUS_CANCELLED = 'CANCELED'
ORDER_STATUS_COMPLETE = 'COMPLETE'
ORDER_STATUS_NEW = 'NEW'
ORDER_STATUS_OPEN = 'OPEN'
ORDER_STATUS_REJECTED = 'REJECTED'
ORDER_STATUS_REPLACED = 'REPLACED'
ORDER_TYPE_BUY = 'BUY'
ORDER_TYPE_SELL = 'SELL'
PRICE_TYPE_LIMIT = 'LIMIT'
PRICE_TYPE_MARKET = 'MARKET'
PRICE_TYPE_SL_LMT = 'SL-LIMIT'
PRICE_TYPE_SL_MKT = 'SL-MARKET'
PRODUCT_TYPE_CNC = 'CNC'
PRODUCT_TYPE_INTRADAY = 'INTRADAY'
PRODUCT_TYPE_NORMAL = 'NORMAL'
SUBSCRIPTION_TYPE_DEPTH = 'DEPTH'
SUBSCRIPTION_TYPE_ORDER = 'ORDER'
SUBSCRIPTION_TYPE_TICK = 'TICK'
TIMEFRAME_TYPE_DAY = 'day'
TIMEFRAME_TYPE_MIN = 'minute'
TIMEFRAME_TYPE_TICK = 'tick'
VALIDITY_TYPE_DAY = 'DAY'
VALIDITY_TYPE_EOS = 'EOS'
VALIDITY_TYPE_IOC = 'IOC'
actid: str
api_session_key: str
base_url: str
exchange_types: list[str]
get_session_keys() tuple[str, str, str, str]

Get stored session keys

Returns:

The session keys

Return type:

tuple[str, str, str, str]

gtt_condition_types: list[str]
login(api_token: str, api_secret: str, totp: str | None = None) None

Login to Definedge Securities Integrate

Parameters:
login_url: str
order_types: list[str]
price_types: list[str]
product_types: list[str]
send_request(route_prefix: str, route: str, method: str, url_params: dict[str, str] | None = None, json_params: dict[str, Any] | None = None, data_params: dict[str, Any] | None = None, query_params: dict[str, str] | None = None, extra_headers: dict[str, str] | None = None) dict[str, Any]

Make an HTTP request.

Parameters:
  • route_prefix (str) – The prefix of the route

  • route (str) – The route

  • method (str) – The HTTP method

  • url_params (dict) – The URL parameters

  • json_params (dict) – The JSON parameters

  • data_params (dict) – The data parameters

  • query_params (dict) – The query parameters

  • extra_headers (dict) – The extra headers

Returns:

The response

Return type:

dict

session_expired_callback: Callable[[], None] | None
set_session_keys(uid: str, actid: str, api_session_key: str, ws_session_key: str) None

Store session keys

Parameters:
  • uid (str) – Your Definedge Securities login UCC id

  • actid (str) – Your Definedge Securities login account id

  • api_session_key (str) – Your Definedge Securities API session key

  • ws_session_key (str) – Your Definedge Securities WebSocket session key

subscription_types: list[str]
property symbols: Generator[dict[str, str], None, None]

Download the master file for symbols and create a generator

Returns:

A generator of symbols

Return type:

Generator[dict[str, str], None, None]

timeframe_types: list[str]
uid: str
ws_session_key: str
class integrate.IntegrateData(connect_to_integrate: ConnectToIntegrate, logging: bool = False)

Bases: object

Definedge Securities Integrate Data API class

Parameters:
  • connect_to_integrate (ConnectToIntegrate) – The connection object.

  • logging (bool) – Enable or disable logging. Defaults to False. If set to True, will print all requests and responses to logger.

historical_data(exchange: str, trading_symbol: str, timeframe: str, start: datetime, end: datetime) Generator[dict[str, Any], None, None]

Retrieve historical data for an security.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • trading_symbol (str) – Trading symbol of the security.

  • timeframe (str) – Timeframe of the data. day or minute are supported.

  • start (datetime) – Start date of the data.

  • end (datetime) – End date of the data.

Returns:

Historical data for the security.

Return type:

Generator[dict[str, Any], None, None]

quotes(exchange: str, trading_symbol: str) dict[str, Any]

Retrieve quotes for an security.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • trading_symbol (str) – Trading symbol of the security.

Returns:

Quote for the security.

Return type:

dict[str, Any]

security_information(exchange: str, trading_symbol: str) dict[str, Any]

Retrieve details about an security.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • trading_symbol (str) – Trading symbol of the security.

Returns:

Details about the security.

Return type:

dict[str, Any]

class integrate.IntegrateOrders(connect_to_integrate: ConnectToIntegrate, logging: bool = False)

Bases: object

Definedge Securities Integrate Orders API class

Parameters:
  • connect_to_integrate (ConnectToIntegrate) – The connection object.

  • logging (bool) – Enable or disable logging. Defaults to False. If set to True, will print all requests and responses to logger.

cancel_gtt_order(alert_id: str) dict[str, Any]

Cancel a GTT order.

Parameters:

alert_id (str) – Alert id of the GTT order.

Returns:

Cancellation response details

Return type:

dict[str, Any]

cancel_oco_order(alert_id: str) dict[str, Any]

Cancel a OCO order.

Parameters:

alert_id (str) – Alert id of the OCO order.

Returns:

Cancellation response details

Return type:

dict[str, Any]

cancel_order(order_id: str) dict[str, Any]

Cancel an order.

Parameters:

order_id (str) – Order ID of the order to be cancelled.

Returns:

Cancellation response details

Return type:

dict[str, Any]

convert_position_product_type(exchange: str, order_type: str, previous_product: str, product_type: str, quantity: int, tradingsymbol: str, position_type: str = 'DAY') dict[str, Any]

Convert an open position’s product type.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • order_type (str) – Order type. Valid values are BUY, SELL.

  • previous_product (str) – Previous product type. Valid values are CNC, INTRADAY, NORMAL.

  • product_type (str) – Product type. Valid values are CNC, INTRADAY, NORMAL.

  • quantity (int) – Quantity to transact.

  • tradingsymbol (str) – Trading symbol of security to transact.

  • position_type (str) – Position type. Valid values are DAY, IOC, EOS.

Returns:

The order details

Return type:

dict[str, Any]

gtt_orders() dict[str, Any]

Get list of GTT orders.

Returns:

List of GTT orders.

Return type:

dict[str, Any]

holdings() dict[str, Any]

Retrieve the list of holdings.

Returns:

List of holdings.

Return type:

dict[str, Any]

limits() dict[str, Any]

Get account balance and cash margin details for all segments.

Returns:

Account balance and cash margin details for all segments.

Return type:

dict[str, Any]

margins(orders: list[dict[str, Any]]) dict[str, Any]

Get margin for a list of orders.

Parameters:

orders (list[dict[str, str]]) – List of orders.

Returns:

Margin for a list of orders.

Return type:

dict[str, Any]

modify_gtt_order(exchange: str, alert_id: str, order_type: str, price: float, quantity: int, tradingsymbol: str, alert_price: float, condition: str) dict[str, Any]

Modify a GTT order.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • alert_id (str) – Alert id of the GTT order.

  • order_type (str) – Order type. Valid values are BUY, SELL.

  • price (float) – Price at which order is to be placed.

  • quantity (int) – Quantity to transact.

  • tradingsymbol (str) – Trading symbol of security to transact.

  • alert_price (float) – Price at which alert is to be triggered.

  • condition (str) – Condition to be met. Valid values are LTP_BELOW, LTP_ABOVE.

Returns:

The order details

Return type:

dict[str, Any]

modify_oco_order(exchange: str, alert_id: str, order_type: str, tradingsymbol: str, stoploss_quantity: int, stoploss_price: float, target_quantity: int, target_price: float, remarks: str | None = None) dict[str, Any]

Modify an OCO order.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • alert_id (str) – Alert id of the OCO order.

  • order_type (str) – Order type. Valid values are BUY, SELL.

  • tradingsymbol (str) – Trading symbol of security to transact.

  • stoploss_quantity (int) – Quantity of stoploss order.

  • stoploss_price (float) – Price of stoploss order.

  • target_quantity (int) – Quantity of target order.

  • target_price (float) – Price of target order.

  • remarks (Union[str, None]) – Remarks if any.

Returns:

The order details

Return type:

dict[str, Any]

modify_order(exchange: str, order_id: str, order_type: str, price: float, price_type: str, product_type: str, quantity: int, tradingsymbol: str, amo: str | None = None, book_loss_price: float | None = None, book_profit_price: float | None = None, disclosed_quantity: int | None = None, market_protection: float | None = None, remarks: str | None = None, trailing_price: float | None = None, trigger_price: float | None = None, validity: str = 'DAY') dict[str, Any]

Modify an open order.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • order_id (str) – Order ID of the order to be modified.

  • order_type (str) – Order type. Valid values are BUY, SELL.

  • price (float) – Price at which order is to be placed. Should be 0 for MARKET order.

  • price_type (str) – Price type. Valid values are MARKET, LIMIT, SL-MARKET, SL-LIMIT.

  • product_type (str) – Product type. Valid values are CNC, INTRADAY, NORMAL.

  • quantity (int) – Quantity to transact.

  • tradingsymbol (str) – Trading symbol of security to transact.

  • amo (str) – If set to True, AMO order will be placed. Defaults to False.

  • book_loss_price (float) – Book loss price (Applicable only for Bracket orders).

  • book_profit_price (float) – Book profit price (Applicable only for Bracket orders).

  • disclosed_quantity (int) – Disclosed quantity for the order (Only for Equity and MCX).

  • market_protection (float) – Market protection percentage for the order (only for BSE and MCX).

  • remarks (str) – Remarks for the order.

  • trailing_price (float) – Trailing price for the order (Applicable only High Leverage product and Bracket order).

  • trigger_price (float) – Trigger price for the order (Applicable only for price_type, SL-MARKET or SL-LIMIT).

  • validity (str) – Validity for the order. Valid values are DAY, IOC, EOS. Defaults to DAY.

Returns:

The order details

Return type:

dict[str, Any]

order(order_id: str) dict[str, Any]

Get status of a order.

Returns:

Order status.

Return type:

dict[str, Any]

orders() dict[str, Any]

Get list of orders.

Returns:

List of orders.

Return type:

dict[str, Any]

place_gtt_order(exchange: str, order_type: str, price: float, quantity: int, tradingsymbol: str, alert_price: float, condition: str) dict[str, Any]

Place a GTT order.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • order_type (str) – Order type. Valid values are BUY, SELL.

  • price (float) – Price at which order is to be placed.

  • quantity (int) – Quantity to transact.

  • tradingsymbol (str) – Trading symbol of security to transact.

  • alert_price (float) – Price at which alert is to be triggered.

  • condition (str) – Condition to be met. Valid values are LTP_BELOW, LTP_ABOVE.

Returns:

The order details

Return type:

dict[str, Any]

place_oco_order(exchange: str, order_type: str, tradingsymbol: str, stoploss_quantity: int, stoploss_price: float, target_quantity: int, target_price: float, remarks: str | None = None) dict[str, Any]

Place an OCO order.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • order_type (str) – Order type. Valid values are BUY, SELL.

  • tradingsymbol (str) – Trading symbol of security to transact.

  • stoploss_quantity (int) – Quantity of stoploss order.

  • stoploss_price (float) – Price of stoploss order.

  • target_quantity (int) – Quantity of target order.

  • target_price (float) – Price of target order.

  • remarks (Union[str, None]) – Remarks if any.

Returns:

The order details

Return type:

dict[str, Any]

place_order(exchange: str, order_type: str, price: float, price_type: str, product_type: str, quantity: int, tradingsymbol: str, algo_id: str, amo: str | None = None, book_loss_price: float | None = None, book_profit_price: float | None = None, disclosed_quantity: int | None = None, market_protection: float | None = None, remarks: str | None = None, trailing_price: float | None = None, trigger_price: float | None = None, validity: str = 'DAY') dict[str, Any]

Place an order.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • order_type (str) – Order type. Valid values are BUY, SELL.

  • price (float) – Price at which order is to be placed. Should be 0 for MARKET order.

  • price_type (str) – Price type. Valid values are MARKET, LIMIT, SL-MARKET, SL-LIMIT.

  • product_type (str) – Product type. Valid values are CNC, INTRADAY, NORMAL.

  • quantity (int) – Quantity to transact.

  • tradingsymbol (str) – Trading symbol of security to transact.

  • algo_id – Algo Id for the order.

  • amo – If set to True, AMO order will be placed. Defaults to False.

  • book_loss_price – Book loss price (Applicable only for Bracket orders).

  • book_profit_price – Book profit price (Applicable only for Bracket orders).

  • disclosed_quantity – Disclosed quantity for the order (Only for Equity and MCX).

  • market_protection – Market protection percentage for the order (only for BSE and MCX).

  • remarks – Remarks for the order.

  • trailing_price – Trailing price for the order (Applicable only High Leverage product and Bracket order).

  • trigger_price – Trigger price for the order (Applicable only for price_type, SL-MARKET or SL-LIMIT).

  • validity – Validity for the order. Valid values are DAY, IOC, EOS. Defaults to DAY.

:type algo_id:str :type amo: str :type book_loss_price: float :type book_profit_price: float :type disclosed_quantity: int :type market_protection: float :type remarks: str :type trailing_price: float :type trigger_price: float :type validity: str :return: The order details :rtype: dict[str, Any]

positions() dict[str, Any]

Retrieve the list of positions.

Returns:

List of positions.

Return type:

dict[str, Any]

slice_order(exchange: str, order_type: str, price: float, price_type: str, product_type: str, quantity: int, slices: int, tradingsymbol: str, amo: str | None = None, book_loss_price: float | None = None, book_profit_price: float | None = None, disclosed_quantity: int | None = None, market_protection: float | None = None, remarks: str | None = None, trailing_price: float | None = None, trigger_price: float | None = None, validity: str = 'DAY') dict[str, Any]

Slice an order.

Parameters:
  • exchange (str) – Exchange in which security is listed. Currently NSE, BSE, NFO, CDS, MCX are supported.

  • order_type (str) – Order type. Valid values are BUY, SELL.

  • price (float) – Price at which order is to be placed. Should be 0 for MARKET order.

  • price_type (str) – Price type. Valid values are MARKET, LIMIT, SL-MARKET, SL-LIMIT.

  • product_type (str) – Product type. Valid values are CNC, INTRADAY, NORMAL.

  • quantity (int) – Quantity to transact.

  • slices (int) – Number of slices.

  • tradingsymbol (str) – Trading symbol of security to transact.

  • amo (str) – If set to True, AMO order will be placed. Defaults to False.

  • book_loss_price (float) – Book loss price (Applicable only for Bracket orders).

  • book_profit_price (float) – Book profit price (Applicable only for Bracket orders).

  • disclosed_quantity (int) – Disclosed quantity for the order (Only for Equity and MCX).

  • market_protection (float) – Market protection percentage for the order (only for BSE and MCX).

  • remarks (str) – Remarks for the order.

  • trailing_price (float) – Trailing price for the order (Applicable only High Leverage product and Bracket order).

  • trigger_price (float) – Trigger price for the order (Applicable only for price_type, SL-MARKET or SL-LIMIT).

  • validity (str) – Validity for the order. Valid values are DAY, IOC, EOS. Defaults to DAY.

Returns:

The order details

Return type:

dict[str, Any]

span_calculator(positions: list[dict[str, Any]]) dict[str, Any]

Get span information for a list of positions.

Parameters:

positions (list[dict[str, str]]) – List of positions.

Returns:

Span information for a list of positions.

Return type:

dict[str, Any]

trades() dict[str, Any]

Retrieve the list of trades executed.

Returns:

List of trades executed.

Return type:

dict[str, Any]

class integrate.IntegrateWebSocket(connect_to_integrate: ConnectToIntegrate, logging: bool = False)

Bases: object

WebSocket client for interacting with Definedge Securities’ streaming quotes, order and depth updates.

Parameters:
  • connect_to_integrate (ConnectToIntegrate) – The connection object.

  • logging (bool) – Enable or disable logging. Defaults to False.

Callbacks

check_token_validity(tokens: list[tuple[str, str]]) None

Check if the given list of security tokens are valid.

Parameters:

tokens (list[tuple[str, str]]) – List of security tokens to check.

Returns:

None

close(code: int | None = None, reason: str | None = None) None

Close the WebSocket connection.

Parameters:
  • code (int) – The close code. Defaults to None.

  • reason (str) – The close reason. Defaults to None.

Returns:

None

close_on_exception(reason: str | None = None) None

Close the WebSocket connection on exception.

Parameters:

reason (str) – The close reason. Defaults to None.

Returns:

None

connect(socket_url: str | None = None, daemonize: bool = False, reconnect: bool = True, reconnect_max_tries: int = 30, reconnect_max_delay: int = 60, connect_timeout: int = 30, ssl_verify: bool = True, proxy: dict[str, str] | None = None) None

Establish a websocket connection with Definedge Securities Integrate.

Parameters:
  • socket_url (str) – The websocket URL to connect to. Defaults to wss://trade.definedgesecurities.com/NorenWSTRTP/.

  • daemonize (bool) – Indicates if the client should run a daemon. Defaults to False.

  • reconnect (bool) – Indicates if the client should auto reconnect. Defaults to True.

  • reconnect_max_tries (int) – Maximum number of retries before it stops reconnecting. Defaults to 30.

  • reconnect_max_delay (int) – Maximum delay after which subsequent reconnection delay will become constant. Defaults to 60.

  • connect_timeout (int) – Maximum time (seconds) for which the API client will wait for a request to complete before it fails. Defaults to 30 seconds.

  • ssl_verify (bool) – Enable or disable SSL verification. Defaults to True.

  • proxy (dict[str, str]) – Proxy URL. Defaults to None.

is_connected() bool

Check if WebSocket connection is established.

Returns:

True if connection is established, else False.

login() None

Login to Definedge Securities Integrate.

Returns:

None

on_acknowledgement(iws: IntegrateWebSocket, ack: dict[str, Any]) None

Callback function called when the WebSocket connection receives an acknowledgement.

Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • ack (dict) – The acknowledgement.

Returns:

None

on_close(iws: IntegrateWebSocket, code: int, reason: str) None

Callback function called when the WebSocket connection is closed. To stop reconnection, use stop method as shown in the example below.

def on_close(iws: IntegrateWebSocket, code: int, reason: str) -> None:
    iws.stop() # this will stop reconnection
Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • code (int) – The close code.

  • reason (str) – The close reason.

Returns:

None

Note:

RFC6455 defines the status codes on connection close.

on_connect(iws: IntegrateWebSocket, response: ConnectionResponse) None

Callback function called when the WebSocket connection is established.

Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • response (ConnectionResponse) – The ConnectionResponse instance.

Returns:

None

on_depth_update(iws: IntegrateWebSocket, depth: dict[str, str]) None

Callback function called when the WebSocket connection receives a depth update.

Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • depth (dict) – The depth update.

Returns:

None

on_error(iws: IntegrateWebSocket, code: int, reason: str) None

Callback function called when the WebSocket connection encounters an error.

Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • code (int) – The error code.

  • reason (str) – The error reason.

Returns:

None

Note:

RFC6455 defines the status codes on connection close.

on_exception(iws: IntegrateWebSocket, e: Exception) None

Callback function called when a Python exception occurs.

Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • e (Exception) – The exception.

Returns:

None

on_login(iws: IntegrateWebSocket) None

Callback function called when the WebSocket connection is logged in.

Parameters:

iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

Returns:

None

on_open(iws: IntegrateWebSocket) None

Callback function called when the WebSocket connection is opened.

Parameters:

iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

Returns:

None

on_order_update(iws: IntegrateWebSocket, order: dict[str, str]) None

Callback function called when the WebSocket connection receives an order update.

Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • order (dict) – The order update.

Returns:

None

on_reconnection(iws: IntegrateWebSocket, retries: int) None

Callback function called when the WebSocket connection is reconnected.

Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • retries (int) – The number of retries.

Returns:

None

on_stop_reconnection(iws: IntegrateWebSocket) None

Callback function called when the WebSocket connection stops retrying to reconnect.

Parameters:

iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

Returns:

None

on_tick_update(iws: IntegrateWebSocket, tick: dict[str, str]) None

Callback function called when the WebSocket connection receives a tick update.

Parameters:
  • iws (IntegrateWebSocket) – The IntegrateWebSocket instance.

  • tick (dict) – The tick update.

Returns:

None

resubscribe() None

Resubscribe to all current subscribed tokens.

Returns:

None

stop() None

Stop the event loop.

Returns:

None

Note:

Should be used if main thread has to be closed in on_close method. Reconnection cannot happen after this method is used.

stop_retry() None

Stop auto retry when it is in progress.

Returns:

None

subscribe(subscription_type: str, tokens: list[tuple[str, str]] | None = None) None

Subscribe to a list of security tokens.

Parameters:
  • subscription_type (str) – The subscription type. Valid values are TICK, ORDER and DEPTH.

  • tokens (list[tuple[str, str]]) – List of security tokens to subscribe to. Defaults to None.

Returns:

None

unsubscribe(unsubscription_type: str, tokens: list[tuple[str, str]] | None = None) None

Unsubscribe the given list of security tokens.

Parameters:
  • unsubscription_type (str) – The unsubscription type. Valid values are TICK, ORDER and DEPTH.

  • tokens (list[tuple[str, str]]) – List of security tokens to unsubscribe from. Defaults to None.

Returns:

None