Sha256: 2f5861133ad426722a4d78bb32e962695a260de3052295d32515152c0fa209a4

Contents?: true

Size: 1.78 KB

Versions: 7

Compression:

Stored size: 1.78 KB

Contents

module KrakenClient
  module Requests
    class Limiter

      attr_reader :config, :previous_timestamps, :endpoint_name, :current_count

      def initialize(config)
        @config              = config
        @previous_timestamps = Time.now
        @current_count       = counter_total
      end

      def update(endpoint_name)
        return unless config.limiter
        @endpoint_name = endpoint_name

        decrement_current_count
      end

      private

      # Adds the number of seconds depending of the current tier value
      def refresh_current_count
        @current_count += ((Time.now - previous_timestamps) / seconds_to_decrement).to_int
        @current_count = counter_total if current_count > counter_total

        current_count
      end

      def decrement_current_count
        @current_count -= value_to_decrement

        if current_count < 0
          sleep value_to_decrement

          @current_count = value_to_decrement

          update(endpoint_name)
        else
          refresh_current_count

          @previous_timestamps = Time.now
        end
      end

      def value_to_decrement

        case endpoint_name
          when 'Ledger'        then 2
          when 'TradeHistory'  then 2
          when 'AddOrder'      then 0
          when 'CancelOrder'   then 0
          else                      1
        end          
      end

      def counter_total
        @counter ||= case config.tier
          when 0 then 10
          when 1 then 10
          when 2 then 10
          when 3 then 20
          when 4 then 20
        end
      end

      def seconds_to_decrement
        @decrement ||= case config.tier
          when 0 then 5
          when 1 then 5
          when 2 then 5
          when 3 then 2
          when 4 then 1
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
kraken_client-1.1.0 lib/kraken_client/requests/limiter.rb
kraken_client-1.0.3 lib/kraken_client/requests/limiter.rb
kraken_client-1.0.2 lib/kraken_client/requests/limiter.rb
kraken_client-1.0.1 lib/kraken_client/requests/limiter.rb
kraken_client-1.0.0 lib/kraken_client/requests/limiter.rb
kraken_client-0.2.1 lib/kraken_client/requests/limiter.rb
kraken_client-0.2.0 lib/kraken_client/requests/limiter.rb