Module: DhanHQ::AI::PromptHelpers

Defined in:
lib/DhanHQ/ai/prompt_helpers.rb

Overview

Helper methods for generating prompts for AI trading assistants.

Provides methods to create system prompts, user prompts, and context summaries for AI models.

Class Method Summary collapse

Class Method Details

.market_analysis(snapshot:, series: nil) ⇒ String

Generate a market analysis prompt.

Parameters:

Returns:

  • (String)

    Market analysis prompt



66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/DhanHQ/ai/prompt_helpers.rb', line 66

def self.market_analysis(snapshot:, series: nil)
  lines = ["=== Market Analysis ==="]
  lines << "Snapshot: #{snapshot.size} instruments"
  lines << "Series: #{series&.size || 0} candles"

  if series&.any?
    lines << "Latest close: ₹#{series.last.close}"
    lines << "Average close: ₹#{series.average_close&.round(2)}"
    lines << "Price range: ₹#{series.price_range&.round(2)}"
  end

  lines.join("\n")
end

.order_confirmation(order_params) ⇒ String

Generate an order confirmation prompt.

Parameters:

  • order_params (Hash)

    Order parameters

Returns:

  • (String)

    Order confirmation prompt



84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/DhanHQ/ai/prompt_helpers.rb', line 84

def self.order_confirmation(order_params)
  <<~PROMPT.strip
    === Order Confirmation Required ===
    #{order_params[:transaction_type]} #{order_params[:quantity]}x #{order_params[:security_id]}
    Exchange: #{order_params[:exchange_segment]}
    Product: #{order_params[:product_type]}
    Type: #{order_params[:order_type]}
    #{order_params[:price] ? "Price: ₹#{order_params[:price]}" : "Market Price"}
    #{"Trigger: ₹#{order_params[:trigger_price]}" if order_params[:trigger_price]}

    Please confirm this order.
  PROMPT
end

.portfolio_summary(holdings:, positions:, funds:) ⇒ String

Generate a portfolio summary prompt.

Parameters:

Returns:

  • (String)

    Portfolio summary



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/DhanHQ/ai/prompt_helpers.rb', line 43

def self.portfolio_summary(holdings:, positions:, funds:)
  # Array() so a missing collection renders as an empty section instead of
  # raising. `funds` was already guarded; these two were not, and a prompt
  # helper failing hard on an empty portfolio is the wrong trade.
  all_holdings = Array(holdings)
  open_positions = Array(positions).select(&:open?)

  lines = ["=== Portfolio Summary ==="]
  lines << "Funds: #{funds.to_prompt}" if funds
  lines << ""
  lines << "Holdings (#{all_holdings.size}):"
  all_holdings.each { |holding| lines << "  #{holding.to_prompt}" }
  lines << ""
  lines << "Open Positions (#{open_positions.size}):"
  open_positions.each { |position| lines << "  #{position.to_prompt}" }
  lines.join("\n")
end

.risk_report(positions:, risk_params: {}) ⇒ String

Generate a risk report prompt.

Parameters:

  • positions (Array<DhanHQ::Models::Position>)

    Current positions

  • risk_params (Hash) (defaults to: {})

    Risk parameters

Returns:

  • (String)

    Risk report



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/DhanHQ/ai/prompt_helpers.rb', line 103

def self.risk_report(positions:, risk_params: {})
  # P&L is summed across every position; only the count is restricted to open
  # ones, since a closed position still contributed realised P&L today.
  all_positions = Array(positions)

  lines = ["=== Risk Report ==="]
  total_unrealized = all_positions.sum { |position| position.unrealized_profit.to_f }
  total_realized = all_positions.sum { |position| position.realized_profit.to_f }

  lines << "Total Unrealized P&L: ₹#{total_unrealized.round(2)}"
  lines << "Total Realized P&L: ₹#{total_realized.round(2)}"
  lines << "Open Positions: #{all_positions.count(&:open?)}"

  lines << "Max Drawdown: #{risk_params[:max_drawdown]}%" if risk_params[:max_drawdown]

  lines << "Daily Loss Limit: ₹#{risk_params[:daily_loss_limit]}" if risk_params[:daily_loss_limit]

  lines.join("\n")
end

.system_prompt(capabilities: []) ⇒ String

Generate a system prompt for an AI trading assistant.

Parameters:

  • capabilities (Array<String>) (defaults to: [])

    List of capabilities

Returns:

  • (String)

    System prompt



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/DhanHQ/ai/prompt_helpers.rb', line 14

def self.system_prompt(capabilities: [])
  <<~PROMPT.strip
    You are an AI trading assistant for Indian stock markets (NSE, BSE, MCX).

    Your capabilities:
    - Fetch market data (LTP, OHLC, quotes)
    - Place, modify, and cancel orders
    - View portfolio holdings, positions, and orders
    - Calculate option Greeks and implied volatility
    - Analyze option chains and Max Pain
    - Apply risk management rules

    #{"Additional capabilities:\n#{capabilities.map { |c| "- #{c}" }.join("\n")}" unless capabilities.empty?}

    Rules:
    - Always confirm before placing live orders
    - Use correlation_id for all agent-originated orders
    - Never expose access tokens or secrets
    - Prefer read-only operations unless explicitly asked to trade
    - Validate instruments before trading using search
  PROMPT
end