Class: DhanHQ::Models::Margin

Inherits:
BaseModel show all
Defined in:
lib/DhanHQ/models/margin.rb

Overview

Model for fetching margin calculation results for orders.

The Margin Calculator API provides span margin, exposure margin, VAR (variable margin), brokerage, leverage, and available margin values for any type of order and instrument you want to place. This helps you determine the margin requirements before placing an order.

Examples:

Calculate margin for a CNC order

margin = DhanHQ::Models::Margin.calculate(
  dhan_client_id: "1000000132",
  exchange_segment: "NSE_EQ",
  transaction_type: "BUY",
  quantity: 5,
  product_type: "CNC",
  security_id: "1333",
  price: 1428.0
)
puts "Total margin required: ₹#{margin.total_margin}"
puts "Available balance: ₹#{margin.available_balance}"

Calculate margin for stop-loss order

margin = DhanHQ::Models::Margin.calculate(
  dhan_client_id: "1000000132",
  exchange_segment: "NSE_EQ",
  transaction_type: "BUY",
  quantity: 10,
  product_type: "INTRADAY",
  security_id: "1333",
  price: 1428.0,
  trigger_price: 1427.0
)
puts "Leverage: #{margin.leverage}x"

Check if sufficient margin is available

margin = DhanHQ::Models::Margin.calculate(params)
if margin.insufficient_balance > 0
  puts "Insufficient balance: ₹#{margin.insufficient_balance}"
else
  puts "Sufficient margin available"
end

Constant Summary collapse

HTTP_PATH =

Base path used to invoke the calculator.

"/v2/margincalculator"

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 inherited from BaseModel

all, api, api_type, #assign_attributes, attributes, create, #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, #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

.calculate(params) ⇒ Margin

Calculates margin requirements for an order before placement.

Fetches span margin, exposure margin, VAR (variable margin), brokerage, leverage, and available margin values for the specified order parameters. This allows you to check margin requirements and availability before actually placing the order.

Examples:

Calculate margin for CNC equity order

margin = DhanHQ::Models::Margin.calculate(
  dhan_client_id: "1000000132",
  exchange_segment: "NSE_EQ",
  transaction_type: "BUY",
  quantity: 5,
  product_type: "CNC",
  security_id: "1333",
  price: 1428.0
)
puts "Total Margin: ₹#{margin.total_margin}"
puts "Brokerage: ₹#{margin.brokerage}"

Parameters:

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

    Request parameters for margin calculation @option params [String] :dhan_client_id (required) User-specific identification generated by Dhan.

    Must be explicitly provided in the params hash
    

    @option params [String] :exchange_segment (required) Exchange and segment identifier.

    Valid values: See {DhanHQ::Constants::MARGIN_CALCULATOR_SEGMENTS} (NSE_EQ, NSE_FNO, BSE_EQ, BSE_FNO, MCX_COMM)
    

    @option params [String] :transaction_type (required) The trading side of transaction.

    Valid values: "BUY", "SELL"
    

    @option params [Integer] :quantity (required) Number of shares for the order. Must be greater than 0 @option params [String] :product_type (required) Product type.

    Valid values: See {DhanHQ::Constants::MARGIN_PRODUCT_TYPES} (CNC, INTRADAY, MARGIN, MTF)
    

    @option params [String] :security_id (required) Exchange standard ID for each scrip @option params [Float] :price (required) Price at which order is placed. Must be greater than 0 @option params [Float] :trigger_price (conditionally required) Price at which the order is triggered.

    Required for STOP_LOSS and STOP_LOSS_MARKET order types
    

Returns:

  • (Margin)

    Margin object containing margin calculation results.

Raises:



102
103
104
105
106
107
108
# File 'lib/DhanHQ/models/margin.rb', line 102

def calculate(params)
  formatted_params = camelize_keys(params)
  validate_params!(formatted_params, DhanHQ::Contracts::MarginCalculatorContract)

  response = resource.calculate(formatted_params)
  new(response, skip_validation: true)
end

.calculate_multi(params) ⇒ Margin

Calculates margin requirements for multiple scripts in a single request.

Provides combined margin calculation including hedge benefit across multiple instruments. Useful for portfolio-level margin analysis.

Examples:

Calculate margin for multiple scripts

margin = DhanHQ::Models::Margin.calculate_multi(
  include_position: true,
  include_orders: true,
  scripts: [
    { exchange_segment: "NSE_EQ", transaction_type: "BUY",
      quantity: 100, product_type: "CNC", security_id: "1333", price: 1428.0 },
    { exchange_segment: "NSE_EQ", transaction_type: "SELL",
      quantity: 50, product_type: "INTRADAY", security_id: "11536", price: 3000.0 }
  ]
)
puts "Total margin: #{margin.total_margin}"

Parameters:

  • params (Hash{Symbol => Object})

    Request parameters @option params [Boolean] :include_position Whether to include existing positions @option params [Boolean] :include_orders Whether to include existing orders @option params [String] :dhan_client_id User-specific identification @option params [Array<Hash>] :scripts Array of instrument margin params, each with:

    - :exchange_segment [String] See {DhanHQ::Constants::MARGIN_CALCULATOR_SEGMENTS}
    - :transaction_type [String] BUY or SELL
    - :quantity [Integer]
    - :product_type [String] See {DhanHQ::Constants::MARGIN_PRODUCT_TYPES}
    - :security_id [String]
    - :price [Float] (required)
    - :trigger_price [Float] (optional)
    

Returns:

  • (Margin)

    Margin object containing combined results.



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/DhanHQ/models/margin.rb', line 144

def calculate_multi(params)
  # Map scripts to scrip_list and include_orders to include_order if provided
  params[:scrip_list] ||= params[:scripts] if params.key?(:scripts)
  params[:include_order] ||= params[:include_orders] if params.key?(:include_orders)
  params[:dhan_client_id] ||= DhanHQ.configuration.client_id

  # Filter only keys supported by the API
  filtered_params = {
    includePosition: params[:include_position],
    includeOrder: params[:include_order],
    dhanClientId: params[:dhan_client_id],
    scripList: params[:scrip_list]
  }

  if filtered_params[:scripList].is_a?(Array)
    filtered_params[:scripList] = filtered_params[:scripList].map do |scrip|
      if scrip.is_a?(Hash)
        {
          exchangeSegment: scrip[:exchange_segment] || scrip[:exchangeSegment],
          transactionType: scrip[:transaction_type] || scrip[:transactionType],
          quantity: scrip[:quantity],
          productType: scrip[:product_type] || scrip[:productType],
          orderType: scrip[:order_type] || scrip[:orderType],
          securityId: scrip[:security_id] || scrip[:securityId],
          price: scrip[:price],
          triggerPrice: scrip[:trigger_price] || scrip[:triggerPrice]
        }.compact
      else
        scrip
      end
    end
  end

  validate_params!(filtered_params, DhanHQ::Contracts::MultiScripMarginCalcRequestContract)
  response = resource.calculate_multi(filtered_params)
  new(response, skip_validation: true)
end

.resourceDhanHQ::Resources::MarginCalculator

Provides a shared instance of the MarginCalculator resource.

Returns:



60
61
62
# File 'lib/DhanHQ/models/margin.rb', line 60

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

Instance Method Details

#to_hHash{Symbol => Float, String}

Converts the Margin model attributes to a hash representation.

Useful for serialization, logging, or passing margin data to other methods.

Returns:

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

    Hash representation of the Margin model.



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/DhanHQ/models/margin.rb', line 189

def to_h
  {
    total_margin: total_margin,
    span_margin: span_margin,
    exposure_margin: exposure_margin || exposure,
    available_balance: available_balance,
    variable_margin: variable_margin,
    insufficient_balance: insufficient_balance,
    brokerage: brokerage,
    leverage: leverage,
    equity_margin: equity_margin,
    fo_margin: fo_margin,
    commodity_margin: commodity_margin || commodity,
    currency: currency,
    hedge_benefit: hedge_benefit
  }.compact
end