module CoinSync::Importers::Kraken::Common

Public Instance Methods

build_transaction_list(entries) click to toggle source
# File lib/coinsync/importers/kraken_common.rb, line 82
def build_transaction_list(entries)
  set = []
  transactions = []

  entries.each do |entry|
    if entry.type == 'transfer'
      transactions << Transaction.new(
        exchange: 'Kraken',
        time: entry.time,
        bought_amount: entry.amount,
        bought_currency: entry.asset,
        sold_amount: BigDecimal(0),
        sold_currency: FiatCurrency.new(nil)
      )
      next
    end

    next if entry.type != 'trade'

    set << entry
    next unless set.length == 2

    if set[0].refid != set[1].refid
      raise "Kraken importer error: Couldn't match a pair of ledger lines - ids don't match: #{set}"
    end

    if set.none? { |e| e.crypto? }
      raise "Kraken importer error: Couldn't match a pair of ledger lines - " +
        "no cryptocurrencies were exchanged: #{set}"
    end

    bought = set.detect { |e| e.amount > 0 }
    sold = set.detect { |e| e.amount < 0 }

    if bought.nil? || sold.nil?
      raise "Kraken importer error: Couldn't match a pair of ledger lines - invalid transaction amounts: #{set}"
    end

    transactions << Transaction.new(
      exchange: 'Kraken',
      time: [bought.time, sold.time].max,
      bought_amount: bought.amount - bought.fee,
      bought_currency: bought.asset,
      sold_amount: -(sold.amount - sold.fee),
      sold_currency: sold.asset
    )

    set.clear
  end

  transactions
end