Class: BitexBot::Robot

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.run!Object

Trade constantly respecting cooldown times so that we don’t get banned by api clients.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/bitex_bot/robot.rb', line 32

def self.run!
  setup
  logger.info("Loading trading robot, ctrl+c *once* to exit gracefully.")
  self.cooldown_until = Time.now
  bot = new
  
  while true
    start_time = Time.now
    next if start_time < cooldown_until
    self.current_cooldowns = 0
    bot.trade!
    # This global sleep is so that we don't stress bitex too much.
    sleep 0.3 unless test_mode
    self.cooldown_until = start_time + current_cooldowns.seconds
  end
end

.setupObject



49
50
51
52
53
# File 'lib/bitex_bot/robot.rb', line 49

def self.setup
  Bitex.api_key = Settings.bitex
  Bitex.sandbox = Settings.sandbox
  taker.setup(Settings)
end

.with_cooldown(&block) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/bitex_bot/robot.rb', line 55

def self.with_cooldown(&block)
  result = block.call
  return result if test_mode
  self.current_cooldowns += 1
  sleep 0.1 
  return result
end

Instance Method Details

#active_closing_flows?Boolean

Returns:

  • (Boolean)


112
113
114
# File 'lib/bitex_bot/robot.rb', line 112

def active_closing_flows?
  BuyClosingFlow.active.exists? || SellClosingFlow.active.exists?
end

#active_opening_flows?Boolean

Returns:

  • (Boolean)


204
205
206
# File 'lib/bitex_bot/robot.rb', line 204

def active_opening_flows?
  BuyOpeningFlow.active.exists? || SellOpeningFlow.active.exists?
end

#finalise_some_opening_flowsObject



86
87
88
89
90
91
# File 'lib/bitex_bot/robot.rb', line 86

def finalise_some_opening_flows
  [BuyOpeningFlow, SellOpeningFlow].each do |kind|
    flows = self.class.graceful_shutdown ? kind.active : kind.old_active
    flows.each{|flow| flow.finalise! }
  end
end

#notify(message) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/bitex_bot/robot.rb', line 208

def notify(message)
  self.class.logger.error(message)
  if Settings.mailer
    mail = Mail.new do
      from Settings.mailer.from
      to Settings.mailer.to
      subject 'Notice from your robot trader'
      body message
    end
    mail.delivery_method(Settings.mailer.method.to_sym,
      Settings.mailer.options.symbolize_keys)
    mail.deliver!
  end
end

#open_positions?Boolean

Returns:

  • (Boolean)


97
98
99
# File 'lib/bitex_bot/robot.rb', line 97

def open_positions?
  OpenBuy.open.exists? || OpenSell.open.exists?
end

#start_closing_flowsObject



93
94
95
# File 'lib/bitex_bot/robot.rb', line 93

def start_closing_flows
  [BuyClosingFlow, SellClosingFlow].each{|kind| kind.close_open_positions}
end

#start_opening_flows_if_neededObject



116
117
118
119
120
121
122
123
124
125
126
127
128
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/bitex_bot/robot.rb', line 116

def start_opening_flows_if_needed
  if store.reload.hold?
    BitexBot::Robot.logger.debug("Not placing new orders because of hold")
    return
  end
  
  if active_closing_flows?
    BitexBot::Robot.logger.debug("Not placing new orders, closing flows.")
    return
  end
  
  if self.class.graceful_shutdown
    BitexBot::Robot.logger.debug("Not placing new orders, shutting down.")
    return
  end
  
  recent_buying, recent_selling =
    [BuyOpeningFlow, SellOpeningFlow].collect do |kind|
      threshold = (Settings.time_to_live / 2).seconds.ago
      kind.active.where('created_at > ?', threshold).first
    end

  if recent_buying && recent_selling
    BitexBot::Robot.logger.debug("Not placing new orders, recent ones exist.")
    return
  end
  
  balances = with_cooldown{ BitexBot::Robot.taker.balance }
  profile = Bitex::Profile.get
  
  total_usd = balances['usd_balance'].to_d + profile[:usd_balance]
  total_btc = balances['btc_balance'].to_d + profile[:btc_balance]
  
  last_log = `tail -c 61440 #{Settings.log.try(:file)}` if Settings.log.try(:file)
  
  store.update_attributes(taker_usd: balances['usd_balance'],
    taker_btc: balances['btc_balance'], log: last_log)
  
  if store.last_warning.nil? || store.last_warning < 30.minutes.ago 
    if store.usd_warning && total_usd <= store.usd_warning
      notify("USD balance is too low, it's #{total_usd},"\
        "make it #{store.usd_warning} to stop this warning.")
      store.update_attributes(last_warning: Time.now)
    end

    if store.btc_warning && total_btc <= store.btc_warning
      notify("BTC balance is too low, it's #{total_btc},"\
        "make it #{store.btc_warning} to stop this warning.")
      store.update_attributes(last_warning: Time.now)
    end
  end

  if store.usd_stop && total_usd <= store.usd_stop
    BitexBot::Robot.logger.debug("Not placing new orders, USD target not met")
    return
  end
  if store.btc_stop && total_btc <= store.btc_stop
    BitexBot::Robot.logger.debug("Not placing new orders, BTC target not met")
    return
  end

  order_book = with_cooldown{ BitexBot::Robot.taker.order_book }
  transactions = with_cooldown{ BitexBot::Robot.taker.transactions }
  
  unless recent_buying
    BuyOpeningFlow.create_for_market(
      balances['btc_available'].to_d,
      order_book['bids'],
      transactions,
      profile[:fee],
      balances['fee'].to_d,
      store)
  end
  unless recent_selling
    SellOpeningFlow.create_for_market(
      balances['usd_available'].to_d,
      order_book['asks'],
      transactions,
      profile[:fee],
      balances['fee'].to_d,
      store)
  end
end

#storeObject

The trader has a Store



224
225
226
# File 'lib/bitex_bot/robot.rb', line 224

def store
  @store ||= Store.first || Store.create
end

#sync_closing_flowsObject



101
102
103
104
105
106
107
108
109
110
# File 'lib/bitex_bot/robot.rb', line 101

def sync_closing_flows
  orders = with_cooldown{ BitexBot::Robot.taker.orders }
  transactions = with_cooldown{ BitexBot::Robot.taker.user_transactions }

  [BuyClosingFlow, SellClosingFlow].each do |kind|
    kind.active.each do |flow|
      flow.sync_closed_positions(orders, transactions)
    end
  end
end

#sync_opening_flowsObject



200
201
202
# File 'lib/bitex_bot/robot.rb', line 200

def sync_opening_flows
  [SellOpeningFlow, BuyOpeningFlow].each{|o| o.sync_open_positions }
end

#trade!Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/bitex_bot/robot.rb', line 67

def trade!
  sync_opening_flows if active_opening_flows?
  finalise_some_opening_flows
  if(!active_opening_flows? && !open_positions? &&
    !active_closing_flows? && self.class.graceful_shutdown)
    self.class.logger.info("Shutdown completed")
    exit
  end
  start_closing_flows if open_positions?
  sync_closing_flows if active_closing_flows?
  start_opening_flows_if_needed
rescue CannotCreateFlow => e
  self.notify("#{e.message}:\n\n#{e.backtrace.join("\n")}")
  sleep (60 * 3) unless self.class.test_mode
rescue StandardError => e
  self.notify("#{e.message}:\n\n#{e.backtrace.join("\n")}")
  sleep 60 unless self.class.test_mode
end

#with_cooldown(&block) ⇒ Object



63
64
65
# File 'lib/bitex_bot/robot.rb', line 63

def with_cooldown(&block)
  self.class.with_cooldown(&block)
end