Class: Stonk::Adapter::AlphaVantageAdapter
- Inherits:
-
Object
- Object
- Stonk::Adapter::AlphaVantageAdapter
- Defined in:
- lib/stonk/adapter/alpha_vantage_adapter.rb
Instance Method Summary collapse
- #get_stock_price(stock_symbol) ⇒ Object
-
#initialize(api_key, retry_on_rate_limit: false, rate_limit_sleep_seconds: 3, rate_limit_retry_count: 10) ⇒ AlphaVantageAdapter
constructor
A new instance of AlphaVantageAdapter.
Constructor Details
#initialize(api_key, retry_on_rate_limit: false, rate_limit_sleep_seconds: 3, rate_limit_retry_count: 10) ⇒ AlphaVantageAdapter
Returns a new instance of AlphaVantageAdapter.
9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/stonk/adapter/alpha_vantage_adapter.rb', line 9 def initialize(api_key, retry_on_rate_limit: false, rate_limit_sleep_seconds: 3, rate_limit_retry_count: 10) @api_key = api_key @base_url = URI("https://alpha-vantage.p.rapidapi.com") @retry_on_rate_limit = retry_on_rate_limit @rate_limit_sleep_seconds = rate_limit_sleep_seconds @rate_limit_retry_count = rate_limit_retry_count @retry_attempts = 0 raise ConfigurationError, "API key is required" if @api_key.nil? raise ConfigurationError, "Rate limit sleep seconds must be greater than 0" if @rate_limit_sleep_seconds < 0 end |
Instance Method Details
#get_stock_price(stock_symbol) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/stonk/adapter/alpha_vantage_adapter.rb', line 21 def get_stock_price(stock_symbol) make_stock_price_request(stock_symbol).dig("Global Quote", "05. price").then do |price| raise Stonk::Adapter::StockNotFound, "Stock price not found for #{stock_symbol}" if price.nil? reset_retry_attempts Stonk::Money.new(price) end rescue Stonk::Adapter::RateLimitExceeded => e raise e unless @retry_on_rate_limit if @retry_attempts >= @rate_limit_retry_count raise Stonk::Adapter::RateLimitRetryExceeded, "Rate limit retry count exceeded" else Stonk.logger.warn("[AlphaVantage] Too many requests for #{stock_symbol}, sleeping for #{@rate_limit_sleep_seconds} seconds") sleep(@rate_limit_sleep_seconds) if @rate_limit_sleep_seconds > 0 register_retry_attempt retry end rescue Net::HTTPError => e raise Stonk::Adapter::ServerError, "Failed to fetch stock price for #{stock_symbol}: #{e.message}" end |