Class: BudaApi::AI::RiskManager

Inherits:
Object
  • Object
show all
Defined in:
lib/buda_api/ai/risk_manager.rb

Overview

AI-powered risk management and portfolio analysis

Constant Summary collapse

RISK_LEVELS =
{
  very_low: { score: 1, color: "๐ŸŸข", description: "Very low risk" },
  low: { score: 2, color: "๐ŸŸก", description: "Low risk" },
  medium: { score: 3, color: "๐ŸŸ ", description: "Medium risk" },
  high: { score: 4, color: "๐Ÿ”ด", description: "High risk" },
  very_high: { score: 5, color: "๐Ÿšซ", description: "Very high risk - avoid!" }
}.freeze
PORTFOLIO_RISK_FACTORS =
[
  "concentration_risk",
  "volatility_risk", 
  "liquidity_risk",
  "correlation_risk",
  "size_risk"
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(client, llm_provider: :openai) ⇒ RiskManager

Returns a new instance of RiskManager.



23
24
25
26
27
28
29
30
31
# File 'lib/buda_api/ai/risk_manager.rb', line 23

def initialize(client, llm_provider: :openai)
  @client = client
  @llm = RubyLLM.new(
    provider: llm_provider,
    system_prompt: build_risk_system_prompt
  )
  
  BudaApi::Logger.info("Risk Manager initialized")
end

Instance Method Details

#analyze_portfolio_risk(options = {}) ⇒ Hash

Analyze portfolio risk across all holdings

Parameters:

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

    analysis options

Options Hash (options):

  • :include_ai_insights (Boolean)

    include AI analysis

  • :focus_factors (Array<String>)

    specific risk factors to analyze

Returns:

  • (Hash)

    comprehensive risk analysis



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/buda_api/ai/risk_manager.rb', line 39

def analyze_portfolio_risk(options = {})
  BudaApi::Logger.info("Analyzing portfolio risk")
  
  begin
    # Get account balances
    balances_result = @client.balances
    portfolios = extract_non_zero_balances(balances_result)
    
    return no_portfolio_risk if portfolios.empty?
    
    # Calculate basic risk metrics
    basic_metrics = calculate_basic_risk_metrics(portfolios)
    
    # Get market data for risk calculations
    market_data = fetch_market_data_for_portfolio(portfolios)
    
    # Calculate advanced risk metrics
    advanced_metrics = calculate_advanced_risk_metrics(portfolios, market_data)
    
    # Generate overall risk assessment
    overall_risk = calculate_overall_risk_score(basic_metrics, advanced_metrics)
    
    result = {
      type: :portfolio_risk_analysis,
      timestamp: Time.now,
      portfolio_value: basic_metrics[:total_value],
      currency_count: portfolios.length,
      overall_risk: overall_risk,
      basic_metrics: basic_metrics,
      advanced_metrics: advanced_metrics,
      recommendations: generate_risk_recommendations(overall_risk, basic_metrics, advanced_metrics),
      holdings: portfolios
    }
    
    # Add AI insights if requested
    if options[:include_ai_insights]
      result[:ai_insights] = generate_ai_risk_insights(result)
    end
    
    result
    
  rescue => e
    error_msg = "Portfolio risk analysis failed: #{e.message}"
    BudaApi::Logger.error(error_msg)
    
    {
      type: :risk_analysis_error,
      error: error_msg,
      timestamp: Time.now
    }
  end
end

#evaluate_trade_risk(market_id, side, amount, price = nil) ⇒ Hash

Evaluate risk for a specific trade before execution

Parameters:

  • market_id (String)

    trading pair

  • side (String)

    โ€˜buyโ€™ or โ€˜sellโ€™

  • amount (Float)

    trade amount

  • price (Float) (defaults to: nil)

    trade price (optional)

Returns:

  • (Hash)

    trade risk assessment



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/buda_api/ai/risk_manager.rb', line 99

def evaluate_trade_risk(market_id, side, amount, price = nil)
  BudaApi::Logger.info("Evaluating trade risk for #{side} #{amount} #{market_id}")
  
  begin
    # Get current market data
    ticker = @client.ticker(market_id)
    order_book = @client.order_book(market_id)
    
    # Get current portfolio
    balances_result = @client.balances
    current_portfolio = extract_non_zero_balances(balances_result)
    
    # Calculate trade impact
    trade_impact = calculate_trade_impact(market_id, side, amount, price, ticker, order_book)
    
    # Calculate position sizing risk
    position_risk = calculate_position_risk(market_id, amount, ticker.last_price.amount, current_portfolio)
    
    # Calculate market impact risk
    market_impact_risk = calculate_market_impact_risk(amount, price || ticker.last_price.amount, order_book)
    
    # Generate overall trade risk score
    trade_risk_score = calculate_trade_risk_score(trade_impact, position_risk, market_impact_risk)
    
    {
      type: :trade_risk_evaluation,
      market_id: market_id,
      side: side,
      amount: amount,
      price: price,
      risk_level: determine_risk_level(trade_risk_score),
      risk_score: trade_risk_score,
      trade_impact: trade_impact,
      position_risk: position_risk,
      market_impact_risk: market_impact_risk,
      recommendations: generate_trade_recommendations(trade_risk_score, trade_impact),
      should_proceed: trade_risk_score < 3.5,
      timestamp: Time.now
    }
    
  rescue => e
    error_msg = "Trade risk evaluation failed: #{e.message}"
    BudaApi::Logger.error(error_msg)
    
    {
      type: :trade_risk_error,
      error: error_msg,
      timestamp: Time.now
    }
  end
end

#monitor_risk_thresholds(thresholds = {}) ⇒ Hash

Monitor portfolio for risk threshold breaches

Parameters:

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

    risk thresholds to monitor

Returns:

  • (Hash)

    monitoring results with alerts



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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/buda_api/ai/risk_manager.rb', line 155

def monitor_risk_thresholds(thresholds = {})
  default_thresholds = {
    max_position_percentage: 30.0,
    max_daily_loss: 5.0,
    min_diversification_score: 0.6,
    max_volatility_score: 4.0
  }
  
  thresholds = default_thresholds.merge(thresholds)
  
  BudaApi::Logger.info("Monitoring risk thresholds")
  
  begin
    # Get current portfolio analysis
    portfolio_analysis = analyze_portfolio_risk
    
    alerts = []
    
    # Check position concentration
    if portfolio_analysis[:basic_metrics][:max_position_percentage] > thresholds[:max_position_percentage]
      alerts << {
        type: :concentration_alert,
        level: :high,
        message: "๐Ÿšจ Position concentration too high: #{portfolio_analysis[:basic_metrics][:max_position_percentage].round(1)}% (limit: #{thresholds[:max_position_percentage]}%)",
        current_value: portfolio_analysis[:basic_metrics][:max_position_percentage],
        threshold: thresholds[:max_position_percentage]
      }
    end
    
    # Check diversification
    if portfolio_analysis[:advanced_metrics][:diversification_score] < thresholds[:min_diversification_score]
      alerts << {
        type: :diversification_alert,
        level: :medium,
        message: "โš ๏ธ Portfolio not well diversified: #{portfolio_analysis[:advanced_metrics][:diversification_score].round(2)} (minimum: #{thresholds[:min_diversification_score]})",
        current_value: portfolio_analysis[:advanced_metrics][:diversification_score],
        threshold: thresholds[:min_diversification_score]
      }
    end
    
    # Check overall volatility
    if portfolio_analysis[:overall_risk][:score] > thresholds[:max_volatility_score]
      alerts << {
        type: :volatility_alert,
        level: :high,
        message: "๐Ÿ”ฅ Portfolio volatility too high: #{portfolio_analysis[:overall_risk][:score].round(1)} (limit: #{thresholds[:max_volatility_score]})",
        current_value: portfolio_analysis[:overall_risk][:score],
        threshold: thresholds[:max_volatility_score]
      }
    end
    
    {
      type: :risk_monitoring,
      timestamp: Time.now,
      alerts_count: alerts.length,
      alerts: alerts,
      thresholds: thresholds,
      portfolio_summary: {
        total_value: portfolio_analysis[:portfolio_value],
        risk_level: portfolio_analysis[:overall_risk][:level],
        risk_score: portfolio_analysis[:overall_risk][:score]
      },
      safe: alerts.empty?
    }
    
  rescue => e
    error_msg = "Risk monitoring failed: #{e.message}"
    BudaApi::Logger.error(error_msg)
    
    {
      type: :risk_monitoring_error,
      error: error_msg,
      timestamp: Time.now
    }
  end
end

#recommend_stop_loss(market_id, position_size) ⇒ Hash

Generate stop-loss recommendations based on risk analysis

Parameters:

  • market_id (String)

    trading pair

  • position_size (Float)

    current position size

Returns:

  • (Hash)

    stop-loss recommendations



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/buda_api/ai/risk_manager.rb', line 237

def recommend_stop_loss(market_id, position_size)
  BudaApi::Logger.info("Generating stop-loss recommendations for #{market_id}")
  
  begin
    ticker = @client.ticker(market_id)
    current_price = ticker.last_price.amount
    
    # Calculate different stop-loss levels
    conservative_stop = current_price * 0.95  # 5% stop loss
    moderate_stop = current_price * 0.90      # 10% stop loss
    aggressive_stop = current_price * 0.85    # 15% stop loss
    
    # Calculate potential losses
    position_value = position_size * current_price
    
    {
      type: :stop_loss_recommendations,
      market_id: market_id,
      current_price: current_price,
      position_size: position_size,
      position_value: position_value,
      recommendations: {
        conservative: {
          price: conservative_stop,
          percentage: 5.0,
          max_loss: position_value * 0.05,
          description: "Conservative 5% stop-loss for capital preservation"
        },
        moderate: {
          price: moderate_stop,
          percentage: 10.0,
          max_loss: position_value * 0.10,
          description: "Moderate 10% stop-loss balancing protection and flexibility"
        },
        aggressive: {
          price: aggressive_stop,
          percentage: 15.0,
          max_loss: position_value * 0.15,
          description: "Aggressive 15% stop-loss for volatile markets"
        }
      },
      recommendation: determine_best_stop_loss(ticker, position_value),
      timestamp: Time.now
    }
    
  rescue => e
    error_msg = "Stop-loss recommendation failed: #{e.message}"
    BudaApi::Logger.error(error_msg)
    
    {
      type: :stop_loss_error,
      error: error_msg,
      timestamp: Time.now
    }
  end
end