Skip to content

Execution Module

Classes:

Name Description
Execution

Execution method to interact with Quantsapp API for trading operations

Execution

Execution method to interact with Quantsapp API for trading operations

Parameters:

Name Type Description Default
session_context SessionContext

The session context for the user got from Login Method

required
order_updates_callback Optional[Callable[[OrderUpdatesWs], Any]]

Callback function to get real-time order updates

None

Methods:

Name Description
add_broker

Add a broker account to Quantsapp account

broker_websocket_reconnect

Force reconnect to broker ws

cancel_all_orders

Cancel all orders from a specific broker account

cancel_orders

Cancel specific orders from specific broker accounts

delete_broker

Delete the broker account from Quantsapp, if exists

get_broker_websocket_status

Get Broker websocket connection status

get_order_log

Get specific order logs from broker end

get_orderbook

Retrieve the order book for a specific broker account.

get_positions

Get positions from a specific broker account

get_positions_combined

Get positions combinely from the specific broker accounts

list_available_brokers

list the brokers based on login mode (ui only & code based)

list_mapped_brokers

List all mapped brokers.

modify_order

Modify an existing order on specific broker accounts

place_order

Place an order on specific broker accounts

add_broker(broker, login_credentials, delete_previous_users=False, update_owner=False)

Add a broker account to Quantsapp account

Parameters:

Name Type Description Default
broker Broker

The broker to add.

required
login_credentials PayloadDhanBrokerLoginCredentials_Type | PayloadChoiceBrokerLoginCredentials_Type

The login credentials for the broker.

required
delete_previous_users bool

Whether to delete previous users

False
update_owner bool

Whether to update the owner

False

Returns:

Type Description
Response_AddBroker

The response object containing the result of the add broker operation.

Example
DHAN
Python
add_dhan_broker_resp = qapp_execution.add_broker(
    broker=qapp_execution.variables.Broker.DHAN,
    login_credentials={
        'access_token': '<DHAN_ACCESS_TOKEN>',
    },
)
if add_dhan_broker_resp.success:
    print(f"Dhan Broker added -> {add_dhan_broker_resp.body = }")
else:
    print(f"Dhan broker failed to add -> {add_dhan_broker_resp.error}")
CHOICE
Python
add_choice_broker_resp = qapp_execution.add_broker(
    broker=qapp_execution.variables.Broker.CHOICE,
    login_credentials={
        'mobile': '1234567890',
        'client_access_token': '<CHOICE_ACCESS_TOKEN>',
    },
)
if add_choice_broker_resp.success:
    print(f"Choice Broker added -> {add_choice_broker_resp.body = }")
else:
    print(f"Choice broker failed to add -> {add_choice_broker_resp.error}")

broker_websocket_reconnect(broker, client_id)

Force reconnect to broker ws

Parameters:

Name Type Description Default
broker Broker

The broker account to reconnect

required
client_id str

The client ID of the broker account to reconnect

required

Returns:

Type Description
Response_BrokerWebsocketReConnect

The response object containing the result of the reconnect operation.

Example
Python
broker_ws_re_conn_resp = qapp_execution.broker_websocket_reconnect(
    broker=qapp_execution.variables.Broker.MSTOCK,
    client_id='<CLIENT_ID>',
)
if broker_ws_re_conn_resp.success:
    print(broker_ws_re_conn_resp.body)
else:
    print(f"Error on ws re-connection -> {broker_ws_re_conn_resp.error}")

cancel_all_orders(broker, client_id)

Cancel all orders from a specific broker account

Parameters:

Name Type Description Default
broker Broker

The broker account to cancel the orders for.

required
client_id str

The client ID of the broker account to cancel the orders for.

required

Returns:

Type Description
Response_CancelAllOrders

The response object containing the result of the cancel orders operation.

Example
Python
cancel_all_orders_resp = qapp_execution.cancel_all_orders(
    broker=qapp_execution.variables.Broker.CHOICE,
    client_id='<CLIENT_ID>',
)
if cancel_all_orders_resp.success:
    print(cancel_all_orders_resp.body)
else:
    print(f"Error on cancel all orders -> {cancel_all_orders_resp.error}")

cancel_orders(orders_to_cancel)

Cancel specific orders from specific broker accounts

Parameters:

Name Type Description Default
orders_to_cancel list[PayloadCancelOrder_Type]

The list of orders to cancel

required

Returns:

Type Description
Response_CancelOrders

The response object containing the result of the cancel orders operation.

Example
Python
cancel_orders_resp = qapp_execution.cancel_orders(
    orders_to_cancel=[
        {
            'broker': qapp_execution.variables.Broker.CHOICE,
            'client_id': '<CLIENT_ID>',
            'order_ids': [
                {
                    'b_orderid': '<BROKER_ORDER_ID>',
                    'e_orderid': '<EXCHANGE_ORDER_ID>',
                },
            ],
        },
        {
            'broker': qapp_execution.variables.Broker.DHAN,
            'client_id': '<CLIENT_ID>',
            'order_ids': [
                {
                    'b_orderid': '<BROKER_ORDER_ID>',
                    'e_orderid': '<EXCHANGE_ORDER_ID>',
                },
            ],
        },
    ],
)
if cancel_orders_resp.success:
    print('Cancel Orders:-')
    pprint(cancel_orders_resp.body)
else:
    print(f"Error on cancel order -> {cancel_orders_resp.error}")

delete_broker(broker, client_id)

Delete the broker account from Quantsapp, if exists

Parameters:

Name Type Description Default
broker Broker

The broker to delete.

required
client_id str

The client ID of the broker account to delete.

required

Returns:

Type Description
Response_DeleteBroker

The response object containing the result of the delete broker operation.

Example
Python
broker_delete_resp = qapp_execution.delete_broker(
    broker=quantsapp.Broker.CHOICE,
    client_id='<CLIENT_ID>',
)
if broker_delete_resp.success:
    print(f"Broker deleted -> {broker_delete_resp.body = }")
else:
    print(f"Broker failed to delete -> {broker_delete_resp.error}")

get_broker_websocket_status(broker, client_id)

Get Broker websocket connection status

Parameters:

Name Type Description Default
broker Broker

The broker account to get the websocket status for

required
client_id str

The client ID of the broker account to get the websocket status for

required

Returns:

Type Description
Response_GetBrokerWebsocketConnectionStatus

The response object containing the result of the get websocket status operation.

Example
Python
get_broker_ws_conn_status_resp = qapp_execution.get_broker_websocket_status(
    broker=qapp_execution.variables.Broker.MSTOCK,
    client_id='<CLIENT_ID>',
)
if get_broker_ws_conn_status_resp.success:
    print(get_broker_ws_conn_status_resp.body)
else:
    print(f"Error on get ws connection status -> {get_broker_ws_conn_status_resp.error}")

get_order_log(broker, client_id, instrument, q_usec)

Get specific order logs from broker end

Parameters:

Name Type Description Default
broker Broker

The broker account to get the order logs for

required
client_id str

The client ID of the broker account to get the order logs for

required
instrument str

The instrument to get the order logs for

required
q_usec datetime

The timestamp to get the order logs for

required

Returns:

Type Description
Response_GetOrderLogs

The response object containing the result of the get order logs operation.

get_orderbook(broker, client_id, resync_from_broker=False, from_cache=True, ascending=False, filters=None)

Retrieve the order book for a specific broker account.

Parameters:

Name Type Description Default
broker Broker

The broker to retrieve the order book for.

required
client_id str

The client ID of the broker account to retrieve the order book for.

required
resync_from_broker bool

Whether to resync the order book from the broker.

False
from_cache bool

Whether to retrieve the order book from cache.

True
ascending bool

Whether to sort the order book in ascending order.

False
filters Optional[PayloadListOrdersFilters_Type]

Optional filters to apply to the order book.

None

Returns:

Type Description
Response_ListOrders

The response object containing the result of the retrieve order book operation.

Example
Python
get_orders_resp = qapp_execution.get_orderbook(
    broker=qapp_execution.variables.Broker.DHAN,
    client_id='<CLIENT_ID>',
    ascending=False,
    from_cache=True,            # Return the orders from either local cache or Quantsapp server
    resync_from_broker=False,   # Resync the orders from Broker api again

    # Optional (any combo of below filters)
    filters={
        'product': qapp_execution.variables.Order.ProductType.INTRADAY,
        'order_status': qapp_execution.variables.Order.Status.CANCELLED,
        'order_type': qapp_execution.variables.Order.OrderType.LIMIT,
        'instrument': 'NIFTY:22-May-25:p:250000',  # instrument structure = 'SYMBOL:EXPIRY:OPTION_TYPE:STRIKE'
    },
)
if get_orders_resp.success:
    print(get_orders_resp.body)
    '''sample
    [
        {
            'b_orderid': '42250523454209',
            'b_usec_update': datetime.datetime(2025, 5, 23, 9, 50, 44, tzinfo=datetime.timezone.utc),
            'broker_client': BrokerClient(broker=Broker.DHAN, client_id='1100735577'),
            'buy_sell': OrderBuySell.BUY,
            'e_orderid': '1200000163510266',
            'instrument': 'NIFTY:05-Jun-25:c:25650',
            'o_ctr': 10,
            'order_status': OrderStatus.CANCELLED,
            'order_type': OrderType.LIMIT,
            'price': 1.45,
            'product_type': OrderProductType.NRML,
            'q_usec': datetime.datetime(2025, 5, 23, 9, 50, 44, tzinfo=datetime.timezone.utc),
            'qty': 75,
            'qty_filled': 0,
            'stop_price': 0.0,
            'userid': 500131
        },
    ]
    '''
else:
    print(f"Error on order listing -> {get_orders_resp.error}")

get_positions(broker_clients, resync_from_broker=False, from_cache=True)

Get positions from a specific broker account

Parameters:

Name Type Description Default
broker_clients list[PayloadGetPositions_Type]

The list of broker clients to get positions for

required
resync_from_broker bool

Whether to resync positions from the broker

False
from_cache bool

Whether to get positions from cache

True

Returns:

Type Description
Response_GetPositions

The response object containing the result of the get positions operation.

Example
Python
get_positions_resp = qapp_execution.get_positions(
    broker_clients=[
        {
            'broker': qapp_execution.variables.Broker.MSTOCK,
            'client_id': '<CLIENT_ID>',
        },
        {
            'broker': qapp_execution.variables.Broker.FIVEPAISA,
            'client_id': '<CLIENT_ID>',
        },
    ],
    resync_from_broker=False,
    from_cache=True,
)
if get_positions_resp.success:
    print(get_positions_resp.body)
else:
    print(f"Error on get positions -> {get_positions_resp.error}")

get_positions_combined(broker_clients, resync_from_broker=False, from_cache=True)

Get positions combinely from the specific broker accounts

Parameters:

Name Type Description Default
broker_clients list[PayloadGetPositions_Type]

The list of broker clients to get positions for

required
resync_from_broker bool

Whether to resync positions from the broker

False
from_cache bool

Whether to get positions from cache

True

Returns:

Type Description
Response_GetPositionsCombined

The response object containing the result of the get positions combined operation.

Example
Python
get_positions_consolidated_resp = qapp_execution.get_positions_combined(
    broker_clients=[
        {
            'broker': qapp_execution.variables.Broker.MSTOCK,
            'client_id': '<CLIENT_ID>',
        },
        {
            'broker': qapp_execution.variables.Broker.CHOICE,
            'client_id': '<CLIENT_ID>',
        },
    ],
    resync_from_broker=False,
    from_cache=True,
)
if get_positions_consolidated_resp.success:
    print(get_positions_consolidated_resp.body)
else:
    print(f"Error on get consolidated positions -> {get_positions_consolidated_resp.error}")

list_available_brokers()

list the brokers based on login mode (ui only & code based)

Returns:

Type Description
Response_ListAvailableBrokers

Response object with list of available brokers

Example
Python
available_brokers = qapp_execution.list_available_brokers()

if available_brokers.success:
    print(available_brokers.body)
    '''sample
    {
        'access_token_login': [
            Broker.CHOICE,
            Broker.DHAN,
        ],
        'oauth_login': [
            Broker.MSTOCK,
            Broker.FIVEPAISA,
            Broker.FIVEPAISA_XTS,
            Broker.FYERS,
            Broker.ZERODHA,
            Broker.MOTILAL_OSWAL,
            Broker.UPSTOX,
            Broker.ALICEBLUE,
            Broker.NUVAMA,
        ]
    }
    '''
else:
    print(f"Error on listing available brokers -> {available_brokers.error}")

if qapp_execution.variables.Broker.CHOICE in available_brokers.body['access_token_login']:
    print('CHOICE broker can be added to Quantsapp via this SDK')

if qapp_execution.variables.Broker.MSTOCK in available_brokers.body['access_token_login']:
    print("MSTOCK broker can't be added to Quantsapp via this SDK. Please add it via https://web.quantsapp.com/broker")

list_mapped_brokers(resync_from_broker=False, from_cache=True)

List all mapped brokers.

Parameters:

Name Type Description Default
resync_from_broker bool

Whether to resync from the broker. Defaults to False.

False
from_cache bool

Whether to get data from cache. Defaults to True.

True

Returns:

Type Description
Response_ListMappedBrokers

The response object containing the list of mapped brokers.

Example
Python
mapped_brokers_resp = qapp_execution.list_mapped_brokers(
    resync_from_broker=False,
    from_cache=False,
)
if mapped_brokers_resp.success:
    print(mapped_brokers_resp.body)
    '''sample
    {
        'brokers': {
            Broker.CHOICE: {
                '<CLIENT_ID>': {
                    'margin': {
                        Exchange.NSE_FNO: 7958.67,
                        'dt': datetime.datetime(2025, 5, 23, 13, 8, 1, tzinfo=datetime.timezone.utc)
                    },
                    'name': '<NAME>',
                    'role': BrokerRole.EXECUTOR,
                    'valid': True,
                    'validity': datetime.datetime(2025, 6, 19, 11, 57, 18, tzinfo=datetime.timezone(datetime.timedelta(seconds=19800), 'IST'))
                }
            },
        },
        'next_margin': datetime.datetime(2025, 5, 23, 13, 23, tzinfo=datetime.timezone.utc),
        'version': 42
    }
    '''
else:
    print(f"Error on getting mapped brokers -> {mapped_brokers_resp.error}")

modify_order(broker, client_id, b_orderid, e_orderid, qty, price, stop_price=None)

Modify an existing order on specific broker accounts

Parameters:

Name Type Description Default
broker Broker

The broker account to modify the order for.

required
client_id str

The client ID of the broker account to modify the order for.

required
b_orderid str

The broker order ID of the order to modify.

required
e_orderid str

The exchange order ID of the order to modify.

required
qty int

The new quantity for the order

required
price float

The new price for the order

required
stop_price Optional[float]

The new stop loss price only incase of Stop Loss type order

None

Returns:

Type Description
Response_ModifyOrder

The response object containing the result of the modify order operation.

Example
Python
modify_order_resp = qapp_execution.modify_order(
    broker=qapp_execution.variables.Broker.CHOICE,
    client_id='<CLIENT_ID>',
    b_orderid='<BROKER_ORDER_ID>',
    e_orderid='<EXCHANGE_ORDER_ID>',
    qty=75,
    price=0.15,
    stop_price=0.05,  # Only for Stop Loss Order
)
if modify_order_resp.success:
    print(modify_order_resp.body)
else:
    print(f"Error on modifying order -> {modify_order_resp.error}")

place_order(broker_accounts, product, order_type, validity, legs, exchange=execution_enums.Exchange.NSE_FNO, margin_benefit=True)

Place an order on specific broker accounts

Parameters:

Name Type Description Default
broker_accounts list[PayloadPlaceOrderBrokerAccounts_Type]

The list of broker accounts to place the order for.

required
product OrderProductType

The product to place the order for.

required
order_type OrderType

The type of order to place.

required
validity OrderValidity

The validity of the order.

required
legs list[PayloadPlaceOrderLeg_Type]

The legs of the order.

required
exchange Exchange

The exchange to place the order on.

NSE_FNO
margin_benefit bool

Whether to apply margin benefit.

True

Returns:

Type Description
Response_PlaceOrder

The response object containing the result of the place order operation.

Example
Python
place_order_resp = qapp_execution.place_order(
    broker_accounts=[
        {
            'broker': qapp_execution.variables.Broker.CHOICE,
            'client_id': '<CLIENT_ID>',
            'lot_multiplier': 1,  # Optional - Default is 1
        }
    ],
    exchange=qapp_execution.variables.Exchange.NSE_FNO,
    product=qapp_execution.variables.Order.ProductType.NRML,
    order_type=qapp_execution.variables.Order.OrderType.LIMIT,
    validity=qapp_execution.variables.Order.Validity.DAY,
    margin_benefit=True,  # Optional - Default = True
    legs=[
        {
            'qty': 75,
            'price': 0.05,
            'instrument': 'NIFTY:26-Jun-25:c:26500',  # Call Option
            'buy_sell': 'b',  # Buy='b', Sell='s'
            # 'stop_price': 5.4,  # Only for Stop Loss Limit Order
        },
        {
            'qty': 75,
            'price': 0.05,
            'instrument': 'NIFTY:26-Jun-25:p:23500',  # Put Option
            'buy_sell': 's',
        },
        {
            'qty': 75,
            'price': 25100,
            'instrument': 'NIFTY:26-Jun-25:x',  # Future
            'buy_sell': 'b',
        },
    ],
)
if place_order_resp.success:
    print(place_order_resp.body)
else:
    print(f"Error on placing order -> {place_order_resp.error}")