Class: DhanHQ::Models::SuperOrder

Inherits:
BaseModel
  • Object
show all
Extended by:
Concerns::BangWrites, Concerns::TrackedWrites
Includes:
Concerns::ApiResponseHandler
Defined in:
lib/DhanHQ/models/super_order.rb

Overview

Note:

Static IP Whitelisting: Super order creation, modification, and cancellation APIs require Static IP whitelisting. Ensure your IP is whitelisted before using these endpoints.

Model for managing multi-leg super orders with smart execution.

Super orders are built for smart execution of trades. They are a collection of orders clubbed into a single order request, which includes an entry leg, target leg, and stop loss leg along with the option to add trailing stop loss. This allows for server-side risk management immediately after entry.

Super orders can be placed across all exchanges and segments, supporting intraday, carry forward, or MTF orders.

Examples:

Create a super order

order = DhanHQ::Models::SuperOrder.create(
  dhan_client_id: "1000000003",
  transaction_type: "BUY",
  exchange_segment: "NSE_EQ",
  product_type: "CNC",
  order_type: "LIMIT",
  security_id: "11536",
  quantity: 5,
  price: 1500,
  target_price: 1600,
  stop_loss_price: 1400,
  trailing_jump: 10
)
puts "Super Order ID: #{order.order_id} - #{order.order_status}"

Modify a super order

order = DhanHQ::Models::SuperOrder.all.first
order.modify(
  leg_name: "ENTRY_LEG",
  price: 1300,
  quantity: 40,
  target_price: 1450,
  stop_loss_price: 1350,
  trailing_jump: 20
)

Cancel a specific leg

order = DhanHQ::Models::SuperOrder.all.first
order.cancel("STOP_LOSS_LEG")

Constant Summary

Constants included from ResponseHelper

ResponseHelper::STATUS_ERROR_FALLBACK

Instance Attribute Summary

Attributes inherited from BaseModel

#attributes, #errors

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Concerns::BangWrites

bang_class_writes, bang_writes

Methods included from Concerns::TrackedWrites

track_class_writes, track_writes

Methods inherited from BaseModel

api, api_type, #assign_attributes, attributes, #delete, #destroy, find, #id, #initialize, #new_record?, #optionchain_api?, parse_collection_response, #persisted?, resource_path, #save, #save!, #to_request_params, #update, #valid?, validate_attributes, validation_contract, #validation_contract, where

Methods included from APIHelper

#handle_response

Methods included from AttributeHelper

#camelize_keys, #deep_camelize_keys, #inspect, #normalize_keys, #snake_case, #titleize_keys

Methods included from ValidationHelper

#valid?, #validate!, #validate_params!

Methods included from RequestHelper

#build_from_response

Constructor Details

This class inherits a constructor from DhanHQ::BaseModel

Class Method Details

.allArray<SuperOrder>

Note:

Order Status: "CLOSED" is used when the ENTRY_LEG and one of either TARGET_LEG or STOP_LOSS_LEG is triggered for entire quantity. "TRIGGERED" status is present for TARGET_LEG and STOP_LOSS_LEG indicating which leg is actually triggered.

Retrieves all super orders placed during the current trading day.

Fetches a special order book that only consists of Super Orders, where the target and stop loss orders are nested under the main entry order leg. Individual legs of each super order can also be found in the main order book with their Order ID.

Examples:

Fetch and analyze super orders

orders = DhanHQ::Models::SuperOrder.all
pending_orders = orders.select { |o| o.order_status == "PENDING" }
pending_orders.each do |order|
  puts "Order: #{order.order_id}"
  puts "Target: ₹#{order.target_price}, Stop Loss: ₹#{order.stop_loss_price}"
  order.leg_details.each do |leg|
    puts "  #{leg[:leg_name]}: ₹#{leg[:price]} (#{leg[:order_status]})"
  end
end

Returns:

  • (Array<SuperOrder>)

    Array of SuperOrder objects. Returns empty array if no orders exist. Each SuperOrder object contains (keys normalized to snake_case):

    • :dhan_client_id [String] User-specific identification generated by Dhan
    • :order_id [String] Order-specific identification generated by Dhan
    • :correlation_id [String] User/partner generated ID for tracking
    • :order_status [String] Last updated status of the order. Valid values: "TRANSIT", "PENDING", "CLOSED", "REJECTED", "CANCELLED", "PART_TRADED", "TRADED"
    • :transaction_type [String] The trading side of transaction. "BUY" or "SELL"
    • :exchange_segment [String] Exchange segment of instrument
    • :product_type [String] Product type. Valid values: "CNC", "INTRADAY", "MARGIN", "MTF"
    • :order_type [String] Order type. "LIMIT" or "MARKET"
    • :validity [String] Validity of order. "DAY"
    • :trading_symbol [String] Trading symbol of the instrument
    • :security_id [String] Exchange standard ID for each scrip
    • :quantity [Integer] Number of shares for the order
    • :remaining_quantity [Integer] Quantity pending execution
    • :ltp [Float] Last Traded Price of the instrument
    • :price [Float] Price at which order is placed
    • :after_market_order [Boolean] Whether the order is placed after market
    • :leg_name [String] Leg identification. "ENTRY_LEG", "TARGET_LEG", "STOP_LOSS_LEG"
    • :trailing_jump [Float] Price jump by which Stop Loss should be trailed
    • :exchange_order_id [String] Exchange generated ID for the order
    • :create_time [String] Time at which the order is created
    • :update_time [String] Last updated time of the order
    • :exchange_time [String] Time at which order was sent to the exchange
    • :oms_error_description [String] Description of error if the order is rejected or failed
    • :average_traded_price [Float] Average price at which order is traded
    • :filled_qty [Integer] Quantity of order traded on Exchange
    • :leg_details [Array] Array of leg details for TARGET_LEG and STOP_LOSS_LEG. Each leg detail contains:
      • :order_id [String] Order ID of the leg
      • :leg_name [String] Leg name ("TARGET_LEG" or "STOP_LOSS_LEG")
      • :transaction_type [String] Transaction type of the leg
      • :total_quatity [Integer] Total quantity (note: typo in API response)
      • :remaining_quantity [Integer] Quantity pending execution
      • :triggered_quantity [Integer] Quantity of Stop Loss or Target leg placed on Exchange
      • :price [Float] Price of the leg
      • :order_status [String] Order status of the leg. "TRIGGERED" indicates the leg has been triggered and placed
      • :trailing_jump [Float] Trailing jump for the leg


144
145
146
147
148
149
# File 'lib/DhanHQ/models/super_order.rb', line 144

def all
  response = resource.all
  return [] unless response.is_a?(Array)

  response.map { |o| new(o, skip_validation: true) }
end

.create(params) ⇒ SuperOrder?

Creates a new super order with entry, target, and stop loss legs.

Places a super order that combines entry, target, and stop-loss legs into one atomic instruction. Supports an optional trailing jump for server-side risk management immediately after entry. Available across all exchanges and segments, supporting intraday, carry-forward, or MTF orders.

Examples:

Create a super order with all legs

order = DhanHQ::Models::SuperOrder.create(
  dhan_client_id: "1000000003",
  transaction_type: "BUY",
  exchange_segment: "NSE_EQ",
  product_type: "CNC",
  order_type: "LIMIT",
  security_id: "11536",
  quantity: 5,
  price: 1500,
  target_price: 1600,
  stop_loss_price: 1400,
  trailing_jump: 10
)
puts "Super Order ID: #{order.order_id}"

Create intraday super order

order = DhanHQ::Models::SuperOrder.create(
  dhan_client_id: "1000000003",
  transaction_type: "SELL",
  exchange_segment: "NSE_EQ",
  product_type: "INTRADAY",
  order_type: "MARKET",
  security_id: "1333",
  quantity: 10,
  price: 2000,
  target_price: 1950,
  stop_loss_price: 2050,
  trailing_jump: 20
)

Parameters:

  • params (Hash{Symbol => String, Integer, Float})

    Super order creation parameters @option params [String] :dhan_client_id (required) User-specific identification generated by Dhan. Must be explicitly provided in the params hash @option params [String] :correlation_id (optional) User/partner generated ID for tracking. Max length: 25 characters @option params [String] :transaction_type (required) The trading side of transaction. Valid values: "BUY", "SELL" @option params [String] :exchange_segment (required) Exchange segment of instrument. Valid values: See Constants::EXCHANGE_SEGMENTS @option params [String] :product_type (required) Product type. Valid values: "CNC", "INTRADAY", "MARGIN", "MTF" @option params [String] :order_type (required) Order type. Valid values: "LIMIT", "MARKET" @option params [String] :security_id (required) Exchange standard ID for each scrip @option params [Integer] :quantity (required) Number of shares for the order. Must be greater than 0 @option params [Float] :price (required) Price at which order is placed. Must be > 0 @option params [Float] :target_price (required) Target price for the Super Order. Must be > 0 @option params [Float] :stop_loss_price (required) Stop loss price for the Super Order. Must be > 0 @option params [Float] :trailing_jump (required) Price jump by which Stop Loss should be trailed. Must be > 0. If set to 0 or omitted, trailing stop loss will be cancelled

Returns:

  • (SuperOrder, nil)

    SuperOrder object with order_id and order_status if creation succeeds, nil otherwise. Response structure:

    • :order_id [String] Order-specific identification generated by Dhan
    • :order_status [String] Last updated status of the order. Valid values: "TRANSIT", "PENDING", "REJECTED"


218
219
220
221
222
223
224
225
226
# File 'lib/DhanHQ/models/super_order.rb', line 218

def create(params)
  normalized_params = snake_case(params)
  config = DhanHQ.configuration
  normalized_params[:dhan_client_id] ||= config.client_id if config&.client_id
  response = resource.create(normalized_params)
  return nil unless response.is_a?(Hash) && response["orderId"]

  new(order_id: response["orderId"], order_status: response["orderStatus"], skip_validation: true)
end

.resourceDhanHQ::Resources::SuperOrders

Provides a shared instance of the SuperOrders resource.

Returns:



76
77
78
# File 'lib/DhanHQ/models/super_order.rb', line 76

def resource
  @resource ||= DhanHQ::Resources::SuperOrders.new
end

Instance Method Details

#cancel(leg_name = DhanHQ::Constants::LegName::ENTRY_LEG) ⇒ Boolean

Note:

The API returns HTTP 202 Accepted on successful cancellation.

Cancels a specific leg of a super order, or the entry leg by default.

Cancels a pending/active super order leg using the order ID and leg name. Cancelling the main entry order ID (ENTRY_LEG) cancels all legs. If a particular target or stop loss leg is cancelled, it cannot be added again.

Examples:

Cancel entry leg (cancels entire super order)

order = DhanHQ::Models::SuperOrder.all.first
if order.cancel("ENTRY_LEG")
  puts "Super order cancelled successfully"
end

Cancel only stop loss leg

order = DhanHQ::Models::SuperOrder.all.first
order.cancel("STOP_LOSS_LEG")

Cancel only target leg

order = DhanHQ::Models::SuperOrder.all.first
order.cancel("TARGET_LEG")

Parameters:

  • leg_name (String) (defaults to: DhanHQ::Constants::LegName::ENTRY_LEG)

    (default: "ENTRY_LEG") Order leg to be cancelled. Valid values: "ENTRY_LEG", "TARGET_LEG", "STOP_LOSS_LEG"

Returns:

  • (Boolean)

    true if cancellation succeeds (order status becomes "CANCELLED"), false otherwise

Raises:

  • (RuntimeError)

    If order ID is missing



336
337
338
339
340
341
342
343
344
345
# File 'lib/DhanHQ/models/super_order.rb', line 336

def cancel(leg_name = DhanHQ::Constants::LegName::ENTRY_LEG)
  raise "Order ID is required to cancel a super order" unless id

  DhanHQ.logger&.info("[DhanHQ::Models::SuperOrder] Cancelling super order #{id} leg #{leg_name}")
  response = self.class.resource.cancel(id, leg_name)
  return false unless response.is_a?(Hash) && response["orderStatus"] == DhanHQ::Constants::OrderStatus::CANCELLED

  DhanHQ.logger&.info("[DhanHQ::Models::SuperOrder] Super order #{id} leg #{leg_name} cancelled successfully")
  true
end

#modify(new_params) ⇒ Boolean

Modifies any leg of a Super Order while it is in PENDING or PART_TRADED state.

The ENTRY_LEG can modify the entire super order and can only be modified when the order status is PENDING or PART_TRADED. Once the entry order status is TRADED, only TARGET_LEG and STOP_LOSS_LEG price and trail jump can be modified.

Examples:

Modify entry leg

order = DhanHQ::Models::SuperOrder.all.first
order.modify(
  dhan_client_id: "1000000009",
  order_id: order.order_id,
  leg_name: "ENTRY_LEG",
  order_type: "LIMIT",
  quantity: 40,
  price: 1300,
  target_price: 1450,
  stop_loss_price: 1350,
  trailing_jump: 20
)

Modify only target leg (after entry is traded)

order = DhanHQ::Models::SuperOrder.all.first
order.modify(
  dhan_client_id: "1000000009",
  order_id: order.order_id,
  leg_name: "TARGET_LEG",
  target_price: 1550
)

Modify stop loss with trailing jump

order = DhanHQ::Models::SuperOrder.all.first
order.modify(
  dhan_client_id: "1000000009",
  order_id: order.order_id,
  leg_name: "STOP_LOSS_LEG",
  stop_loss_price: 1250,
  trailing_jump: 15
)

Parameters:

  • new_params (Hash{Symbol => String, Integer, Float})

    Fields to modify @option new_params [String] :dhan_client_id (required) User-specific identification generated by Dhan. Must be explicitly provided in the params hash @option new_params [String] :order_id (required) Order-specific identification generated by Dhan @option new_params [String] :leg_name (required) Leg to modify. Valid values:

    - "ENTRY_LEG" - Entire Super Order can be modified, only when main order status
    is "PENDING" or "PART_TRADED"
    - "TARGET_LEG" - Target leg can be modified
    - "STOP_LOSS_LEG" - Stop loss leg can be modified
    

    @option new_params [String] :order_type (conditionally required) Order type. Required for ENTRY_LEG. Valid values: "LIMIT", "MARKET" @option new_params [Integer] :quantity (conditionally required) Quantity to be modified. Required for ENTRY_LEG @option new_params [Float] :price (conditionally required) Price to be modified. Required for ENTRY_LEG @option new_params [Float] :target_price (conditionally required) Target price to be modified. Required for ENTRY_LEG or TARGET_LEG @option new_params [Float] :stop_loss_price (conditionally required) Stop loss price to be modified. Required for ENTRY_LEG or STOP_LOSS_LEG @option new_params [Float] :trailing_jump (conditionally required) Stop loss price jump to be modified. Required for ENTRY_LEG or STOP_LOSS_LEG. If set to 0 or not provided, trailing stop loss will be cancelled

Returns:

  • (Boolean)

    true if modification succeeds (orderId matches), false otherwise

Raises:

  • (RuntimeError)

    If order ID is missing



295
296
297
298
299
300
301
302
303
304
# File 'lib/DhanHQ/models/super_order.rb', line 295

def modify(new_params)
  raise "Order ID is required to modify a super order" unless id

  DhanHQ.logger&.info("[DhanHQ::Models::SuperOrder] Modifying super order #{id}")
  response = self.class.resource.update(id, new_params)
  return false unless response.is_a?(Hash) && response["orderId"] == id

  DhanHQ.logger&.info("[DhanHQ::Models::SuperOrder] Super order #{id} modified successfully")
  true
end