data

package
v0.0.0-...-01d81e3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 16, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package data provides services for all market data DhanHQ APIs.

This package includes services for:

  • Quote: LTP, OHLC, and full market quotes
  • Historical: Intraday and daily candle data
  • Options: Option chain and expiry lists
  • Depth: Full market depth (20 levels)
  • Instruments: Instrument list download and search

Quote Service

The QuoteService provides market quotes:

// Build a quote request
req := data.NewQuoteRequest().
    AddNSE("1333", "2885").
    AddNSEFNO("35001")

// Get LTP quotes
quotes, err := client.Quote.GetLTP(ctx, req)

// Get full quotes with depth
quotes, err := client.Quote.GetFullQuote(ctx, req)

Historical Service

The HistoricalService provides OHLC candle data:

// Get daily candles
candles, err := client.Historical.GetDaily(ctx, "1333", models.ExchangeNSE,
    data.InstrumentEquity, "2024-01-01", "2024-01-31")

// Get intraday candles
candles, err := client.Historical.GetIntraday(ctx, "1333", models.ExchangeNSE,
    data.InstrumentEquity, models.Resolution5Min, "2024-01-15", "2024-01-15")

// Convenience methods
candles, err := client.Historical.GetDailyLastNDays(ctx, "1333", models.ExchangeNSE,
    data.InstrumentEquity, 30)

Options Service

The OptionsService provides option chain data:

// Get expiry dates
expiries, err := client.Options.GetExpiryList(ctx, "13", models.ExchangeNFO)

// Get option chain
chain, err := client.Options.GetOptionChain(ctx, "13", models.ExchangeNFO, expiries[0])

// Helper functions
atmStrike := data.GetATMStrike(chain)
filtered := data.FilterOptionChain(chain, &data.OptionChainFilter{StrikesAroundATM: 5})

Depth Service

The DepthService provides market depth with analysis:

depth, err := client.Depth.GetMarketDepthSingle(ctx, models.ExchangeNSE, "1333")
analysis := data.AnalyzeDepth(depth)
fmt.Printf("Spread: %.2f%%\n", analysis.SpreadPercentage)

Instrument Service

The InstrumentService provides instrument list management:

// Download instruments
err := client.LoadInstruments(ctx)

// Search
instruments := client.Instruments.SearchBySymbol("RELIANCE")
futures := client.Instruments.GetFutures("NIFTY")

Index

Constants

View Source
const (
	InstrumentEquity    = "EQUITY"
	InstrumentFuture    = "FUTIDX"
	InstrumentFutstk    = "FUTSTK"
	InstrumentOption    = "OPTIDX"
	InstrumentOptstk    = "OPTSTK"
	InstrumentIndex     = "INDEX"
	InstrumentCurrency  = "FUTCUR"
	InstrumentCommodity = "FUTCOM"
)

InstrumentType constants for historical data

View Source
const (
	ExpiryCurrentMonth = 0
	ExpiryNextMonth    = 1
	ExpiryFarMonth     = 2
)

ExpiryCode constants

Variables

View Source
var InstrumentListURLs = struct {
	NSE_EQ   string
	NSE_FNO  string
	BSE_EQ   string
	BSE_FNO  string
	MCX      string
	NSE_CURR string
	ALL      string
}{
	NSE_EQ:   "https://images.dhan.co/api-data/api-scrip-master-equities.csv",
	NSE_FNO:  "https://images.dhan.co/api-data/api-scrip-master-derivatives.csv",
	BSE_EQ:   "https://images.dhan.co/api-data/api-scrip-master-equities.csv",
	BSE_FNO:  "https://images.dhan.co/api-data/api-scrip-master-derivatives.csv",
	MCX:      "https://images.dhan.co/api-data/api-scrip-master-commodities.csv",
	NSE_CURR: "https://images.dhan.co/api-data/api-scrip-master-currencies.csv",
	ALL:      "https://images.dhan.co/api-data/api-scrip-master.csv",
}

InstrumentListURLs contains URLs for instrument lists

Functions

func FilterOptionChain

func FilterOptionChain(chain *models.OptionChain, filter *OptionChainFilter) []models.OptionChainEntry

FilterOptionChain filters option chain entries based on criteria

func FormatDate

func FormatDate(t time.Time) string

FormatDate formats time.Time to API date format (YYYY-MM-DD)

func FormatDateRange

func FormatDateRange(days int) (fromDate, toDate string)

FormatDateRange returns from and to date strings for last N days

func GetATMStrike

func GetATMStrike(chain *models.OptionChain) float64

GetATMStrike returns the at-the-money strike price

func GetBestBidAsk

func GetBestBidAsk(depth *models.MarketDepth) (bestBid, bestAsk float64)

GetBestBidAsk returns the best bid and ask prices

func GetITMStrikes

func GetITMStrikes(chain *models.OptionChain, optionType models.OptionType, count int) []models.OptionChainEntry

GetITMStrikes returns in-the-money strikes

func GetMidPrice

func GetMidPrice(depth *models.MarketDepth) float64

GetMidPrice returns the mid price between best bid and ask

func GetOTMStrikes

func GetOTMStrikes(chain *models.OptionChain, optionType models.OptionType, count int) []models.OptionChainEntry

GetOTMStrikes returns out-of-the-money strikes

func GetVWAP

func GetVWAP(depth *models.MarketDepth, levels int) float64

GetVWAP calculates volume-weighted average price from depth

Types

type CandleResponse

type CandleResponse struct {
	Open         []float64 `json:"open"`
	High         []float64 `json:"high"`
	Low          []float64 `json:"low"`
	Close        []float64 `json:"close"`
	Volume       []int64   `json:"volume"`
	Timestamp    []int64   `json:"timestamp"`
	OpenInterest []int64   `json:"open_interest,omitempty"`
}

CandleResponse represents the API response for candle data

func (*CandleResponse) ToCandles

func (r *CandleResponse) ToCandles() []models.Candle

ToCandles converts the response to a slice of Candle

type DailyRequest

type DailyRequest struct {
	SecurityID      string `json:"securityId"`
	ExchangeSegment string `json:"exchangeSegment"`
	Instrument      string `json:"instrument"`
	ExpiryCode      int    `json:"expiryCode,omitempty"`
	FromDate        string `json:"fromDate"`
	ToDate          string `json:"toDate"`
}

DailyRequest represents a request for daily historical data

type DepthAnalysis

type DepthAnalysis struct {
	// TotalBidQuantity sum of all bid quantities
	TotalBidQuantity int64

	// TotalAskQuantity sum of all ask quantities
	TotalAskQuantity int64

	// BidAskRatio ratio of bid to ask quantity
	BidAskRatio float64

	// WeightedBidPrice volume-weighted average bid price
	WeightedBidPrice float64

	// WeightedAskPrice volume-weighted average ask price
	WeightedAskPrice float64

	// Spread difference between best ask and best bid
	Spread float64

	// SpreadPercentage spread as percentage of mid price
	SpreadPercentage float64

	// BidDepth number of bid levels
	BidDepth int

	// AskDepth number of ask levels
	AskDepth int

	// Imbalance order imbalance indicator (-1 to 1)
	Imbalance float64
}

DepthAnalysis provides analysis of market depth

func AnalyzeDepth

func AnalyzeDepth(depth *models.MarketDepth) *DepthAnalysis

AnalyzeDepth analyzes market depth and returns key metrics

type DepthService

type DepthService struct {
	// contains filtered or unexported fields
}

DepthService handles market depth operations

func NewDepthService

func NewDepthService(client *httpclient.Client) *DepthService

NewDepthService creates a new DepthService

func (*DepthService) GetMarketDepth

func (s *DepthService) GetMarketDepth(ctx context.Context, req *QuoteRequest) (map[string]models.MarketDepth, error)

GetMarketDepth retrieves full market depth (20 levels) for given securities

func (*DepthService) GetMarketDepthSingle

func (s *DepthService) GetMarketDepthSingle(ctx context.Context, exchange models.Exchange, securityID string) (*models.MarketDepth, error)

GetMarketDepthSingle retrieves market depth for a single security

type ExpiredOptionData

type ExpiredOptionData struct {
	StrikePrice float64           `json:"strikePrice"`
	OptionType  models.OptionType `json:"optionType"`
	Candles     []models.Candle   `json:"candles"`
}

ExpiredOptionData represents historical option data

type ExpiredOptionsRequest

type ExpiredOptionsRequest struct {
	UnderlyingScrip string `json:"UnderlyingScrip"`
	UnderlyingSeg   string `json:"UnderlyingSeg"`
	Expiry          string `json:"Expiry"`
	FromDate        string `json:"FromDate"`
	ToDate          string `json:"ToDate"`
}

ExpiredOptionsRequest for fetching expired options data

type ExpiryListRequest

type ExpiryListRequest struct {
	UnderlyingScrip string `json:"UnderlyingScrip"`
	UnderlyingSeg   string `json:"UnderlyingSeg"`
}

ExpiryListRequest represents a request for expiry dates

type HistoricalService

type HistoricalService struct {
	// contains filtered or unexported fields
}

HistoricalService handles historical data operations

func NewHistoricalService

func NewHistoricalService(client *httpclient.Client) *HistoricalService

NewHistoricalService creates a new HistoricalService

func (*HistoricalService) GetDaily

func (s *HistoricalService) GetDaily(ctx context.Context, securityID string, exchange models.Exchange, instrument string, fromDate, toDate string) ([]models.Candle, error)

GetDaily retrieves daily historical candle data

func (*HistoricalService) GetDailyLastNDays

func (s *HistoricalService) GetDailyLastNDays(ctx context.Context, securityID string, exchange models.Exchange, instrument string, days int) ([]models.Candle, error)

GetDailyLastNDays retrieves daily data for last N days

func (*HistoricalService) GetDailyWithExpiry

func (s *HistoricalService) GetDailyWithExpiry(ctx context.Context, securityID string, exchange models.Exchange, instrument string, expiryCode int, fromDate, toDate string) ([]models.Candle, error)

GetDailyWithExpiry retrieves daily data for derivatives with expiry code

func (*HistoricalService) GetIntraday

func (s *HistoricalService) GetIntraday(ctx context.Context, securityID string, exchange models.Exchange, instrument string, interval models.ChartResolution, fromDate, toDate string) ([]models.Candle, error)

GetIntraday retrieves intraday candle data

func (*HistoricalService) GetIntradayByDate

func (s *HistoricalService) GetIntradayByDate(ctx context.Context, securityID string, exchange models.Exchange, instrument string, interval models.ChartResolution, date time.Time) ([]models.Candle, error)

GetIntradayByDate retrieves intraday data for a specific date

func (*HistoricalService) GetIntradayToday

func (s *HistoricalService) GetIntradayToday(ctx context.Context, securityID string, exchange models.Exchange, instrument string, interval models.ChartResolution) ([]models.Candle, error)

GetIntradayToday retrieves intraday data for today

func (*HistoricalService) GetMultipleIntraday

func (s *HistoricalService) GetMultipleIntraday(ctx context.Context, requests []IntradayRequest) (map[string][]models.Candle, error)

GetMultipleIntraday retrieves intraday data for multiple securities

type InstrumentService

type InstrumentService struct {
	// contains filtered or unexported fields
}

InstrumentService handles instrument list operations with optimized indexing

func NewInstrumentService

func NewInstrumentService(client *httpclient.Client) *InstrumentService

NewInstrumentService creates a new InstrumentService

func (*InstrumentService) ClearCache

func (s *InstrumentService) ClearCache()

ClearCache clears the instrument cache and all indexes

func (*InstrumentService) DownloadInstruments

func (s *InstrumentService) DownloadInstruments(ctx context.Context, url string) ([]models.Instrument, error)

DownloadInstruments downloads and parses the instrument list with indexed storage

func (*InstrumentService) GetByExchange

func (s *InstrumentService) GetByExchange(exchange models.Exchange) []models.Instrument

GetByExchange retrieves all instruments for an exchange using index - O(m) where m = instruments in exchange

func (*InstrumentService) GetByInstrumentType

func (s *InstrumentService) GetByInstrumentType(instType models.InstrumentType) []models.Instrument

GetByInstrumentType retrieves instruments by type using index - O(m)

func (*InstrumentService) GetCacheSize

func (s *InstrumentService) GetCacheSize() int

GetCacheSize returns the number of cached instruments

func (*InstrumentService) GetFutures

func (s *InstrumentService) GetFutures(underlying string) []models.Instrument

GetFutures retrieves all futures instruments using index

func (*InstrumentService) GetIndexStats

func (s *InstrumentService) GetIndexStats() map[string]int

GetIndexStats returns statistics about the indexes

func (*InstrumentService) GetInstrument

func (s *InstrumentService) GetInstrument(exchange models.Exchange, securityID string) (*models.Instrument, bool)

GetInstrument retrieves an instrument by exchange and security ID - O(1) lookup

func (*InstrumentService) GetOptions

func (s *InstrumentService) GetOptions(underlying string, optionType models.OptionType) []models.Instrument

GetOptions retrieves all options instruments using index

func (*InstrumentService) IsCacheValid

func (s *InstrumentService) IsCacheValid() bool

IsCacheValid checks if the instrument cache is still valid

func (*InstrumentService) SearchByName

func (s *InstrumentService) SearchByName(name string) []models.Instrument

SearchByName searches instruments by name - O(n)

func (*InstrumentService) SearchBySymbol

func (s *InstrumentService) SearchBySymbol(symbol string) []models.Instrument

SearchBySymbol searches instruments by trading symbol using index - O(1) for exact, O(n) for partial

func (*InstrumentService) SearchBySymbolExact

func (s *InstrumentService) SearchBySymbolExact(symbol string) []models.Instrument

SearchBySymbolExact searches for exact symbol match - O(1)

type IntradayRequest

type IntradayRequest struct {
	SecurityID      string `json:"securityId"`
	ExchangeSegment string `json:"exchangeSegment"`
	Instrument      string `json:"instrument"`
	Interval        string `json:"interval"`
	FromDate        string `json:"fromDate"`
	ToDate          string `json:"toDate"`
}

IntradayRequest represents a request for intraday data

type OptionChainFilter

type OptionChainFilter struct {
	// MinStrike minimum strike price
	MinStrike float64

	// MaxStrike maximum strike price
	MaxStrike float64

	// StrikesAroundATM number of strikes around ATM
	StrikesAroundATM int

	// OptionType filter by CE or PE (empty for both)
	OptionType models.OptionType
}

OptionChainFilter provides filtering options for option chain

type OptionChainRequest

type OptionChainRequest struct {
	UnderlyingScrip string `json:"UnderlyingScrip"`
	UnderlyingSeg   string `json:"UnderlyingSeg"`
	Expiry          string `json:"Expiry"`
}

OptionChainRequest represents a request for option chain

type OptionsService

type OptionsService struct {
	// contains filtered or unexported fields
}

OptionsService handles option chain and related operations

func NewOptionsService

func NewOptionsService(client *httpclient.Client) *OptionsService

NewOptionsService creates a new OptionsService

func (*OptionsService) GetExpiredOptionsData

func (s *OptionsService) GetExpiredOptionsData(ctx context.Context, underlyingSecurityID string, exchange models.Exchange, expiry, fromDate, toDate string) ([]ExpiredOptionData, error)

GetExpiredOptionsData retrieves historical data for expired options

func (*OptionsService) GetExpiryList

func (s *OptionsService) GetExpiryList(ctx context.Context, underlyingSecurityID string, exchange models.Exchange) ([]string, error)

GetExpiryList retrieves available expiry dates for an underlying

func (*OptionsService) GetOptionChain

func (s *OptionsService) GetOptionChain(ctx context.Context, underlyingSecurityID string, exchange models.Exchange, expiry string) (*models.OptionChain, error)

GetOptionChain retrieves the option chain for an underlying

type QuoteRequest

type QuoteRequest struct {
	// NSE_EQ securities from NSE Equity
	NSE_EQ []string `json:"NSE_EQ,omitempty"`

	// NSE_FNO securities from NSE F&O
	NSE_FNO []string `json:"NSE_FNO,omitempty"`

	// NSE_CURR securities from NSE Currency
	NSE_CURR []string `json:"NSE_CURR,omitempty"`

	// BSE_EQ securities from BSE Equity
	BSE_EQ []string `json:"BSE_EQ,omitempty"`

	// BSE_FNO securities from BSE F&O
	BSE_FNO []string `json:"BSE_FNO,omitempty"`

	// BSE_CURR securities from BSE Currency
	BSE_CURR []string `json:"BSE_CURR,omitempty"`

	// MCX_COMM securities from MCX
	MCX_COMM []string `json:"MCX_COMM,omitempty"`

	// IDX_NSE Index from NSE
	IDX_NSE []string `json:"IDX_NSE,omitempty"`

	// IDX_BSE Index from BSE
	IDX_BSE []string `json:"IDX_BSE,omitempty"`
}

QuoteRequest represents a request for quotes

func NewQuoteRequest

func NewQuoteRequest() *QuoteRequest

NewQuoteRequest creates a new empty quote request

func (*QuoteRequest) AddBSE

func (r *QuoteRequest) AddBSE(securityIDs ...string) *QuoteRequest

AddBSE adds BSE equity securities to the request

func (*QuoteRequest) AddBSEIndex

func (r *QuoteRequest) AddBSEIndex(securityIDs ...string) *QuoteRequest

AddBSEIndex adds BSE index to the request

func (*QuoteRequest) AddMCX

func (r *QuoteRequest) AddMCX(securityIDs ...string) *QuoteRequest

AddMCX adds MCX commodity securities to the request

func (*QuoteRequest) AddNSE

func (r *QuoteRequest) AddNSE(securityIDs ...string) *QuoteRequest

AddNSE adds NSE equity securities to the request

func (*QuoteRequest) AddNSEFNO

func (r *QuoteRequest) AddNSEFNO(securityIDs ...string) *QuoteRequest

AddNSEFNO adds NSE F&O securities to the request

func (*QuoteRequest) AddNSEIndex

func (r *QuoteRequest) AddNSEIndex(securityIDs ...string) *QuoteRequest

AddNSEIndex adds NSE index to the request

type QuoteService

type QuoteService struct {
	// contains filtered or unexported fields
}

QuoteService handles market quote operations

func NewQuoteService

func NewQuoteService(client *httpclient.Client) *QuoteService

NewQuoteService creates a new QuoteService

func (*QuoteService) GetFullQuote

func (s *QuoteService) GetFullQuote(ctx context.Context, req *QuoteRequest) (map[string]models.FullQuote, error)

GetFullQuote retrieves complete market data for given securities

func (*QuoteService) GetFullQuoteSingle

func (s *QuoteService) GetFullQuoteSingle(ctx context.Context, exchange models.Exchange, securityID string) (*models.FullQuote, error)

GetFullQuoteSingle retrieves full quote for a single security (convenience method)

func (*QuoteService) GetLTP

func (s *QuoteService) GetLTP(ctx context.Context, req *QuoteRequest) (map[string]models.LTPQuote, error)

GetLTP retrieves Last Traded Price for given securities

func (*QuoteService) GetLTPSingle

func (s *QuoteService) GetLTPSingle(ctx context.Context, exchange models.Exchange, securityID string) (*models.LTPQuote, error)

GetLTPSingle retrieves LTP for a single security (convenience method)

func (*QuoteService) GetOHLC

func (s *QuoteService) GetOHLC(ctx context.Context, req *QuoteRequest) (map[string]models.OHLCQuote, error)

GetOHLC retrieves OHLC data for given securities

func (*QuoteService) GetOHLCSingle

func (s *QuoteService) GetOHLCSingle(ctx context.Context, exchange models.Exchange, securityID string) (*models.OHLCQuote, error)

GetOHLCSingle retrieves OHLC for a single security (convenience method)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL