Class: RAPFLAG::History

Inherits:
Object
  • Object
show all
Defined in:
lib/rapflag/fetch.rb

Constant Summary collapse

DATE_FORMAT =
'%Y.%m.%d'
DATE_TIME_FORMAT =
'%Y.%m.%d %H:%M:%S'
@@btc_to_usd =
{}
@@bfx_to_usd =
{}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(wallet = 'trading', currency = 'USD') ⇒ History

Returns a new instance of History.



15
16
17
18
# File 'lib/rapflag/fetch.rb', line 15

def initialize(wallet = 'trading', currency = 'USD')
  @wallet = wallet
  @currency = currency
end

Instance Attribute Details

#bfx_to_usdObject (readonly)

Returns the value of attribute bfx_to_usd.



9
10
11
# File 'lib/rapflag/fetch.rb', line 9

def bfx_to_usd
  @bfx_to_usd
end

#btc_to_usdObject (readonly)

Returns the value of attribute btc_to_usd.



9
10
11
# File 'lib/rapflag/fetch.rb', line 9

def btc_to_usd
  @btc_to_usd
end

#currencyObject (readonly)

Returns the value of attribute currency.



9
10
11
# File 'lib/rapflag/fetch.rb', line 9

def currency
  @currency
end

#historyObject (readonly)

Returns the value of attribute history.



9
10
11
# File 'lib/rapflag/fetch.rb', line 9

def history
  @history
end

#walletObject (readonly)

Returns the value of attribute wallet.



9
10
11
# File 'lib/rapflag/fetch.rb', line 9

def wallet
  @wallet
end

Instance Method Details

#create_csv_fileObject

Configure the client with the proper KEY/SECRET, you can create a new one from: www.bitfinex.com/api



88
89
90
91
92
93
94
95
96
97
98
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
# File 'lib/rapflag/fetch.rb', line 88

def create_csv_file
  out_file = "output/#{@wallet}_#{@currency}.csv"
  FileUtils.makedirs(File.dirname(out_file))
  CSV.open(out_file,'w',
      :write_headers=> true,
      :headers => ['currency',
                  'amount',
                  'balance',
                  'description',
                  'date_time',
                  ] #< column header
    ) do |csv|
    @history.each do | hist_item|
      csv << [ hist_item['currency'],
              hist_item['amount'],
              hist_item['balance'],
              hist_item['description'],
                Time.at(hist_item['timestamp'].to_i).strftime(DATE_TIME_FORMAT),
              ]
    end
  end

  sums = {}
  @history.each do | hist_item|
    key = /^[^\d]+/.match(hist_item['description'])[0].chomp
    value = hist_item['amount'].to_f
    if sums[key]
      sums[key] +=  value
    else
      sums[key]  =  value
    end
  end

  puts
  puts "Summary for #{@wallet} #{@currency} (#{@history.size} entries}"
  sums.each do |key, value|
    puts " #{sprintf('%40s', key)} is #{value}"
  end
end

#create_summaryObject



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/rapflag/fetch.rb', line 129

def create_summary
  @daily = {}
  @history.sort{|x,y| x['timestamp'] <=> y['timestamp']}.each do | hist_item|
    date = Time.at(hist_item['timestamp'].to_i).strftime(DATE_FORMAT)
    info = Struct::Daily.new(date, hist_item['amount'].to_f, hist_item['balance'].to_f, hist_item['description'])
    amount = hist_item['amount'].to_f
    balance = hist_item['balance'].to_f
    if @daily[date]
      old_balance = @daily[date]
      existing = @daily[date]
    else
      info.income = 0.0
      existing = info
    end
    if /Wire Withdrawal fee|Trading fees for|Margin Funding Payment on wallet/i.match( hist_item['description'])
      existing.income += amount
    end
    existing.balance = balance if balance != 0.0
    @daily[date] = existing
  end
  out_file = "output/#{@wallet}_#{@currency}_summary.csv"
  FileUtils.makedirs(File.dirname(out_file))
  CSV.open(out_file,'w',
      :write_headers=> true,
      :headers => ['currency',
                   'date',
                  'income',
                  'balance',
                  'rate',
                  'balance_in_usd',
                  ] #< column header
    ) do |csv|
    @daily.each do |date, info|
      strings = date.split('.')
      fetch_date = Date.new(strings[0].to_i, strings[1].to_i, strings[2].to_i)
      rate = get_usd_exchange(fetch_date, @currency)
      csv << [@currency,
              date,
              info.income,
              info.balance,
              rate ? rate : nil,
              rate ? info.balance * get_usd_exchange(fetch_date, @currency) : nil,
             ]
    end
  end
end

#fetch_csv_historyObject



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/rapflag/fetch.rb', line 61

def fetch_csv_history
  client = Bitfinex::Client.new
  @history = []
  timestamp = Time.now.to_i + 1
  while true
    begin
      partial = client.history(@currency, { :limit => 500, :until => timestamp, :wallet => @wallet})
      break unless partial && partial.size > 0
      if partial.is_a?(Hash)
        puts "Got #{partial['error']} while fetching #{@wallet} #{@currency} until #{Time.at(timestamp)}"
        exit 3
      end
      first_time = Time.at(partial.first['timestamp'].to_i).strftime(DATE_TIME_FORMAT)
      last_time = Time.at(partial.last['timestamp'].to_i).strftime(DATE_TIME_FORMAT)
      puts "Feched #{partial.size} @history entries #{first_time} -> #{last_time}"  if $VERBOSE
      timestamp = (partial.last['timestamp'].to_i - 1)
      @history = @history | partial
      break if partial.size <= 1
    rescue => error
      puts "error #{error}"
    end
  end
  puts "Feched #{@history.size} history entries" if $VERBOSE
end

#get_usd_exchange(date_time = Time.now, from = 'BTC') ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/rapflag/fetch.rb', line 20

def get_usd_exchange(date_time = Time.now, from='BTC')
  return 1.0 if from == 'USD'
  key = date_time.strftime(DATE_FORMAT)
  return @@btc_to_usd[key] if from.eql?('BTC') && @@btc_to_usd.size > 0
  return @@bfx_to_usd[key] if from.eql?('BFX') && @@bfx_to_usd.size > 0

  ms =  (date_time.is_a?(Date) ? date_time.to_time : date_time).to_i*1000
  ms_next_date = ms + (3*24*3600)*1000
  # this does not work
  # url = "https://api.bitfinex.com/v2/candles/trade:1D:t#{from}USD/hist?start:#{ms}?end:#{ms_next_date}"
  url = "https://api.bitfinex.com/v2/candles/trade:1D:t#{from}USD/hist?start:#{ms}?end:#{ms_next_date}"
  # therefore we just return the most uptodate
  url = "https://api.bitfinex.com/v2/candles/trade:1D:t#{from}USD/hist?start:#{ms}"
  puts "Fetching #{date_time}: #{url} #{@@btc_to_usd.size} BTC #{@@bfx_to_usd.size} BFX" if $VERBOSE
  response = Faraday.get(url)
  items = eval(response.body)
  rates = {}
  items.each do |item|
    if item.first.eql?(:error)
      puts "Fetching returned #{item}. Aborting"
      exit(1)
    end
    # http://docs.bitfinex.com/v2/reference#rest-public-candles
    # field definitions for  [ MTS, OPEN, CLOSE, HIGH, LOW, VOLUME ],
    # MTS   int   millisecond time stamp
    # OPEN  float   First execution during the time frame
    # CLOSE   float   Last execution during the time frame
    # HIGH  integer   Highest execution during the time frame
    # LOW   float   Lowest execution during the timeframe
    # VOLUME  float   Quantity of symbol traded within the timeframe
    # [[1489363200000,1224.4,1211.2,1238,1206.7,6157.96283895],
    timestamp = Time.at(item.first/1000).strftime(DATE_FORMAT)
    rates[timestamp] = item[2]
  end;
  from.eql?('BTC') ? @@btc_to_usd = rates.clone : @@bfx_to_usd = rates.clone
  rates[key] ? rates[key] : nil
rescue => err
  puts "Err #{err}"
  binding.pry if defined?(MiniTest)
end