Class: CexioReinvestor::Trader

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

Instance Method Summary collapse

Constructor Details

#initialize(username, api_key, api_secret) ⇒ Trader



9
10
11
12
13
# File 'lib/cexio_reinvestor.rb', line 9

def initialize(username, api_key, api_secret)
  @username = username
  @api_key = api_key
  @api_secret = api_secret
end

Instance Method Details

#apiObject



15
16
17
# File 'lib/cexio_reinvestor.rb', line 15

def api
  @api ||= CEX::API.new(@username, @api_key, @api_secret)
end

#runObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/cexio_reinvestor.rb', line 47

def run
  while true do
    [ 'GHS/BTC', 'GHS/NMC' ].each do |pair|
      case trade(pair)
      when :timeout
        puts "Timed out when trying to contact CEX.io."
      when :invalid_response
        puts "Hit CEX.io API request limit, will sleep for a bit."
        sleep 240
      end
      sleep 120
    end
  end
end

#trade(pair) ⇒ Object



19
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
# File 'lib/cexio_reinvestor.rb', line 19

def trade(pair)
  to, from = pair.split('/')
  balance = BigDecimal.new(api.balance[from]['available'])
  sleep 1
  price = BigDecimal.new(api.ticker(pair)['ask'], 8)
  sleep 1
  amount_to_buy = (balance / price).round(8, :down)
  return if amount_to_buy < MIN

  result = api.place_order('buy', amount_to_buy, price, pair)
  result['pending'] = BigDecimal.new(result.fetch('pending', 0), 8)

  order_info = "#{amount_to_buy.to_s('F')} #{to} @ #{price.to_s('F')} #{from} each"
  if result['error']
    print "Could not place order for #{order_info}"
    puts " - Error was: #{result['error']}"
  else
    print "Placed order for #{order_info}"
    print " - Bought #{(amount_to_buy - result['pending']).to_s('F')}"
    print ", #{result['pending'].to_s('F')} pending" if result['pending'] > 0
    puts " - #{Time.now}"
  end
rescue Timeout::Error
  :timeout
rescue JSON::ParserError
  :invalid_response
end