Class: Bitfinex::WSv2

Inherits:
Object
  • Object
show all
Includes:
Emittr::Events
Defined in:
lib/ws/ws2.rb

Overview

Implements version 2 of the Bitfinex WebSocket API, taking an evented approach. Incoming packets trigger event broadcasts with names relevant to the individual packets. Provides order manipulation methods that support callback blocks, which are called when the relevant confirmation notifications are received

Constant Summary collapse

INFO_SERVER_RESTART =
20051
INFO_MAINTENANCE_START =
20060
INFO_MAINTENANCE_END =
20061
FLAG_DEC_S =

enables all decimals as strings

8,         # enables all decimals as strings
FLAG_TIME_S = 32,       # enables all timestamps as strings
FLAG_TIMESTAMP = 32768, # timestamps in milliseconds
FLAG_SEQ_ALL = 65536,   # enable sequencing
FLAG_CHECKSUM = 131072

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ WSv2

Creates a new instance of the class

Parameters:

  • params (Hash) (defaults to: {})
  • params.url (string)
    • connection URL

  • params.api_key (string)
  • params.api_secret (string)
  • params.manage_order_books (boolean)
    • if true, order books are persisted internally, allowing for automatic checksum verification

  • params.transform (boolean)
    • if true, full models are returned in place of array data

  • params.seq_audit (boolean)
    • enables automatic seq number verification

  • params.checksum_audit (boolean)
    • enables automatic OB checksum verification (requires manage_order_books)



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

def initialize (params = {})
  @l = Logger.new(STDOUT)
  @l.progname = 'ws2'

  @url = params[:url] || 'wss://api.bitfinex.com/ws/2'
  @api_key = params[:api_key]
  @api_secret = params[:api_secret]
  @manage_obs = params[:manage_order_books]
  @transform = !!params[:transform]
  @seq_audit = !!params[:seq_audit]
  @checksum_audit = !!params[:checksum_audit]

  @enabled_flags = 0
  @is_open = false
  @is_authenticated = false
  @channel_map = {}
  @order_books = {}
  @pending_blocks = {}
  @last_pub_seq = nil
  @last_auth_seq = nil
end

Instance Method Details

#auth!(calc = 0, dms = 0) ⇒ Object

Authenticates the socket connection

Parameters:

  • calc (number) (defaults to: 0)
  • dms (number) (defaults to: 0)
    • dead man switch, active 4



624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
# File 'lib/ws/ws2.rb', line 624

def auth! (calc = 0, dms = 0)
  if @is_authenticated
    raise Exception, 'already authenticated'
  end

  auth_nonce = new_nonce
  auth_payload = "AUTH#{auth_nonce}#{auth_nonce}"
  sig = sign(auth_payload)

  @ws.send(JSON.generate({
    :event => 'auth',
    :apiKey => @api_key,
    :authSig => sig,
    :authPayload => auth_payload,
    :authNonce => auth_nonce,
    :dms => dms,
    :calc => calc
  }))
end

#cancel_order(order, &cb) ⇒ Object

Cancel an order by ID

Parameters:

  • order (Hash|Array|Order|number)
    • must contain or be ID

  • cb (Block)
    • triggered upon receipt of confirmation notification



683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
# File 'lib/ws/ws2.rb', line 683

def cancel_order (order, &cb)
  return if !@is_authenticated

  if order.is_a?(Numeric)
    id = order
  elsif order.is_a?(Array)
    id = order[0]
  elsif order.instance_of?(Models::Order)
    id = order.id
  elsif order.kind_of?(Hash)
    id = order[:id] || order['id']
  else
    raise Exception, 'tried to cancel order with invalid ID'
  end

  @ws.send(JSON.generate([0, 'oc', nil, { :id => id }]))

  if !cb.nil?
    @pending_blocks["order-cancel-#{id}"] = cb
  end
end

#close!Object

Closes the websocket client



136
137
138
# File 'lib/ws/ws2.rb', line 136

def close!
  @ws.close
end

#enable_flag(flag) ⇒ Object

Enable an individual flag (see FLAG_* constants)

Parameters:

  • flag (number)


578
579
580
581
582
583
584
585
# File 'lib/ws/ws2.rb', line 578

def enable_flag (flag)
  return unless @is_open

  @ws.send(JSON.generate({
    :event => 'conf',
    :flags => @enabled_flags | flag
  }))
end

#enable_ob_checksums(audit = true) ⇒ Object

Sets the flag to activate order book checksums. Managed order books are required for automatic checksum audits.

Parameters:

  • audit (boolean) (defaults to: true)
    • if true (default), incoming checksums will be compared to local checksums



613
614
615
616
# File 'lib/ws/ws2.rb', line 613

def enable_ob_checksums (audit = true)
  @checksum_audit = audit
  enable_flag(FLAG_CHECKSUM)
end

#enable_sequencing(audit = true) ⇒ Object

Sets the flag to activate sequence numbers on incoming packets

Parameters:

  • audit (boolean) (defaults to: true)
    • if true (default), incoming seq numbers will be checked for consistency



602
603
604
605
# File 'lib/ws/ws2.rb', line 602

def enable_sequencing (audit = true)
  @seq_audit = audit
  enable_flag(FLAG_SEQ_ALL)
end

#handle_auth_event(msg) ⇒ Object

:nodoc:



506
507
508
509
510
511
512
513
514
515
516
517
# File 'lib/ws/ws2.rb', line 506

def handle_auth_event (msg) # :nodoc:
  if msg['status'] != 'OK'
    @l.error "auth failed: #{msg['message']}"
    return
  end

  @channel_map[msg['chanId']] = { 'channel' => 'auth' }
  @is_authenticated = true
  emit(:auth, msg)

  @l.info 'authenticated'
end

#handle_auth_message(msg, chan) ⇒ Object

:nodoc:



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
# File 'lib/ws/ws2.rb', line 359

def handle_auth_message (msg, chan) # :nodoc:
  type = msg[1]
  return if type == 'hb'
  payload = msg[2]

  case type
  when 'n'
    emit(:notification, @transform ? Models::Notification.new(payload) : payload)
    handle_notification_promises(payload)
  when 'te'
    emit(:trade_entry, @transform ? Models::Trade.new(payload) : payload)
  when 'tu'
    emit(:trade_update, @transform ? Models::Trade.new(payload) : payload)
  when 'os'
    emit(:order_snapshot, @transform ? payload.map { |o| Models::Order.new(o) } : payload)
  when 'ou'
    emit(:order_update, @transform ? Models::Order.new(payload) : payload)
  when 'on'
    emit(:order_new, @transform ? Models::Order.new(payload) : payload)
  when 'oc'
    emit(:order_close, @transform ? Models::Order.new(payload) : payload)
  when 'ps'
    emit(:position_snapshot, @transform ? payload.map { |p| Models::Position.new(p) } : payload)
  when 'pn'
    emit(:position_new, @transform ? Models::Position.new(payload) : payload)
  when 'pu'
    emit(:position_update, @transform ? Models::Position.new(payload) : payload)
  when 'pc'
    emit(:position_close, @transform ? Models::Position.new(payload) : payload)
  when 'fos'
    emit(:funding_offer_snapshot, @transform ? payload.map { |fo| Models::FundingOffer.new(fo) } : payload)
  when 'fon'
    emit(:funding_offer_new, @transform ? Models::FundingOffer.new(payload) : payload)
  when 'fou'
    emit(:funding_offer_update, @transform ? Models::FundingOffer.new(payload) : payload)
  when 'foc'
    emit(:funding_offer_close, @transform ? Models::FundingOffer.new(payload) : payload)
  when 'fcs'
    emit(:funding_credit_snapshot, @transform ? payload.map { |fc| Models::FundingCredit.new(fc) } : payload)
  when 'fcn'
    emit(:funding_credit_new, @transform ? Models::FundingCredit.new(payload) : payload)
  when 'fcu'
    emit(:funding_credit_update, @transform ? Models::FundingCredit.new(payload) : payload)
  when 'fcc'
    emit(:funding_credit_close, @transform ? Models::FundingCredit.new(payload) : payload)
  when 'fls'
    emit(:funding_loan_snapshot, @transform ? payload.map { |fl| Models::FundingLoan.new(fl) } : payload)
  when 'fln'
    emit(:funding_loan_new, @transform ? Models::FundingLoan.new(payload) : payload)
  when 'flu'
    emit(:funding_loan_update, @transform ? Models::FundingLoan.new(payload) : payload)
  when 'flc'
    emit(:funding_loan_close, @transform ? Models::FundingLoan.new(payload) : payload)
  when 'ws'
    emit(:wallet_snapshot, @transform ? payload.map { |w| Models::Wallet.new(payload) } : payload)
  when 'wu'
    emit(:wallet_update, @transform ? Models::Wallet.new(payload) : payload)
  when 'bu'
    emit(:balance_update, @transform ? Models::BalanceInfo.new(payload) : payload)
  when 'miu'
    emit(:margin_info_update, @transform ? Models::MarginInfo.new(payload) : payload)
  when 'fiu'
    emit(:funding_info_update, @transform ? Models::FundingInfo.new(payload) : payload)
  when 'fte'
    emit(:funding_trade_entry, @transform ? Models::FundingTrade.new(payload) : payload)
  when 'ftu'
    emit(:funding_trade_update, @transform ? Models::FundingTrade.new(payload) : payload)
  end
end

#handle_candles_message(msg, chan) ⇒ Object

:nodoc:



258
259
260
261
262
263
264
265
266
# File 'lib/ws/ws2.rb', line 258

def handle_candles_message (msg, chan) # :nodoc:
  payload = msg[1]

  if payload[0].kind_of?(Array)
    emit(:candles, chan['key'], @transform ? payload.map { |c| Models::Candle.new(c) } : payload)
  else
    emit(:candles, chan['key'], @transform ? Models::Candle.new(payload) : payload)
  end
end

#handle_config_event(msg) ⇒ Object

:nodoc:



552
553
554
555
556
557
558
559
# File 'lib/ws/ws2.rb', line 552

def handle_config_event (msg) # :nodoc:
  if msg['status'] != 'OK'
    @l.error "config failed: #{msg['message']}"
  else
    @l.info "flags updated to #{msg['flags']}"
    @enabled_flags = msg['flags']
  end
end

#handle_error_event(msg) ⇒ Object

:nodoc:



548
549
550
# File 'lib/ws/ws2.rb', line 548

def handle_error_event (msg) # :nodoc:
  @l.error msg
end

#handle_info_event(msg) ⇒ Object

:nodoc:



519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
# File 'lib/ws/ws2.rb', line 519

def handle_info_event (msg) # :nodoc:
  if msg.include?('version')
    if msg['version'] != 2
      close!
      raise Exception, "server not running API v2: #{msg['version']}"
    end

    platform = msg['platform']

    @l.info "server running API v2 (platform: %s (%d))" % [
      platform['status'] == 0 ? 'under maintenance' : 'operating normally',
      platform['status']
    ]
  elsif msg.include?('code')
    code = msg['code']

    if code == INFO_SERVER_RESTART
      @l.info 'server restarted, please reconnect'
      emit(:server_restart)
    elsif code == INFO_MAINTENANCE_START
      @l.info 'server maintenance period started!'
      emit(:maintenance_start)
    elsif code == INFO_MAINTENANCE_END
      @l.info 'server maintenance period ended!'
      emit(:maintenance_end)
    end
  end
end

#handle_notification_promises(n) ⇒ Object

Resolves/rejects any pending promise associated with the notification



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/ws/ws2.rb', line 310

def handle_notification_promises (n) # :nodoc:
  type = n[1]
  payload = n[4]
  status = n[6]
  msg = n[7]

  return unless payload.kind_of?(Array) # expect order payload

  case type
  when 'on-req'
    cid = payload[2]
    k = "order-new-#{cid}"

    return unless @pending_blocks.has_key?(k)

    if status == 'SUCCESS'
      @pending_blocks[k].call(@transform ? Models::Order.new(payload) : payload)
    else
      @pending_blocks[k].call(Exception.new("#{status}: #{msg}"))
    end

    @pending_blocks.delete(k)
  when 'oc-req'
    id = payload[0]
    k = "order-cancel-#{id}"

    return unless @pending_blocks.has_key?(k)

    if status == 'SUCCESS'
      @pending_blocks[k].call(payload)
    else
      @pending_blocks[k].call(Exception.new("#{status}: #{msg}"))
    end

    @pending_blocks.delete(k)
  when 'ou-req'
    id = payload[0]
    k = "order-update-#{id}"

    return unless @pending_blocks.has_key?(k)

    if status == 'SUCCESS'
      @pending_blocks[k].call(@transform ? Models::Order.new(payload) : payload)
    else
      @pending_blocks[k].call(Exception.new("#{status}: #{msg}"))
    end
  end
end

#handle_order_book_checksum_message(msg, chan) ⇒ Object

:nodoc:



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/ws/ws2.rb', line 268

def handle_order_book_checksum_message (msg, chan) # :nodoc:
  key = "#{chan['symbol']}:#{chan['prec']}:#{chan['len']}"
  emit(:checksum, chan['symbol'], msg)

  return unless @manage_obs
  return unless @order_books.has_key?(key)

  remote_cs = msg[2]
  local_cs = @order_books[key].checksum

  if local_cs != remote_cs
    err = "OB checksum mismatch, have #{local_cs} want #{remote_cs} [#{chan['symbol']}"
    @l.error err
    emit(:error, err)
  else
    @l.info "OB checksum OK #{local_cs} [#{chan['symbol']}]"
  end
end

#handle_order_book_message(msg, chan) ⇒ Object

:nodoc:



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/ws/ws2.rb', line 287

def handle_order_book_message (msg, chan) # :nodoc:
  ob = msg[1]

  if @manage_obs
    key = "#{chan['symbol']}:#{chan['prec']}:#{chan['len']}"

    if !@order_books.has_key?(key)
      @order_books[key] = Models::OrderBook.new(ob, chan['prec'][0] == 'R')
    else
      @order_books[key].update_with(ob)
    end

    data = @order_books[key]
  elsif @transform
    data = Models::OrderBook.new(ob)
  else
    data = ob
  end

  emit(:order_book, chan['symbol'], data)
end

#handle_subscribed_event(msg) ⇒ Object

:nodoc:



561
562
563
564
565
# File 'lib/ws/ws2.rb', line 561

def handle_subscribed_event (msg) # :nodoc:
  @l.info "subscribed to #{msg['channel']} [#{msg['chanId']}]"
  @channel_map[msg['chanId']] = msg
  emit(:subscribed, msg['chanId'])
end

#handle_ticker_message(msg, chan) ⇒ Object

:nodoc:



230
231
232
233
234
235
236
237
238
# File 'lib/ws/ws2.rb', line 230

def handle_ticker_message (msg, chan) # :nodoc:
  payload = msg[1]

  if chan['symbol'][0] === 't'
    emit(:ticker, chan['symbol'], @transform ? Models::TradingTicker.new(payload) : payload)
  else
    emit(:ticker, chan['symbol'], @transform ? Models::FundingTicker.new(payload) : payload)
  end
end

#handle_trades_message(msg, chan) ⇒ Object

:nodoc:



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/ws/ws2.rb', line 240

def handle_trades_message (msg, chan) # :nodoc:
  if msg[1].kind_of?(Array)
    payload = msg[1]
    emit(:public_trades, chan['symbol'], @transform ? payload.map { |t| Models::PublicTrade.new(t) } : payload)
  else
    payload = @transform ? Models::PublicTrade.new(msg[2]) : msg[2]
    type = msg[1]

    emit(:public_trades, chan['symbol'], payload)

    if type == 'te'
      emit(:public_trade_entry, chan['symbol'], payload)
    elsif type == 'tu'
      emit(:public_trade_update, chan['symbol'], payload)
    end
  end
end

#handle_unsubscribed_event(msg) ⇒ Object

:nodoc:



567
568
569
570
571
# File 'lib/ws/ws2.rb', line 567

def handle_unsubscribed_event (msg) # :nodoc:
  @l.info "unsubscribed from #{msg['chanId']}"
  @channel_map.delete(msg['chanId'])
  emit(:unsubscribed, msg['chanId'])
end

#is_flag_enabled(flag) ⇒ boolean

Checks if an individual flag is enabled (see FLAG_* constants)

Parameters:

  • flag (number)

Returns:

  • (boolean)

    enabled



593
594
595
# File 'lib/ws/ws2.rb', line 593

def is_flag_enabled (flag)
  (@enabled_flags & flag) == flag
end

#new_nonceObject

:nodoc:



644
645
646
# File 'lib/ws/ws2.rb', line 644

def new_nonce # :nodoc:
  Time.now.to_i.to_s
end

#on_close(e) ⇒ Object

:nodoc:



102
103
104
105
106
# File 'lib/ws/ws2.rb', line 102

def on_close (e) # :nodoc:
  @l.info 'client closed'
  @is_open = false
  emit(:close)
end

#on_message(e) ⇒ Object

:nodoc:



93
94
95
96
97
98
99
100
# File 'lib/ws/ws2.rb', line 93

def on_message (e) # :nodoc:
  @l.info "recv #{e.data}"

  msg = JSON.parse(e.data)
  process_message(msg)

  emit(:message, msg)
end

#on_open(e) ⇒ Object

:nodoc:



84
85
86
87
88
89
90
91
# File 'lib/ws/ws2.rb', line 84

def on_open (e) # :nodoc:
  @l.info 'client open'
  @is_open = true
  emit(:open)

  enable_sequencing if @seq_audit
  enable_ob_checksums if @checksum_audit
end

#open!Object

Opens the websocket client inside an eventmachine run block



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/ws/ws2.rb', line 111

def open!
  if @is_open
    raise Exception, 'already open'
  end

  EM.run {
    @ws = Faye::WebSocket::Client.new(@url)

    @ws.on(:open) do |e|
      on_open(e)
    end

    @ws.on(:message) do |e|
      on_message(e)
    end

    @ws.on(:close) do |e|
      on_close(e)
    end
  }
end

#process_channel_message(msg) ⇒ Object

:nodoc:



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/ws/ws2.rb', line 199

def process_channel_message (msg) # :nodoc:
  if !@channel_map.include?(msg[0])
    @l.error "recv message on unknown channel: #{msg[0]}"
    return
  end

  chan = @channel_map[msg[0]]
  type = msg[1]

  if msg.size < 2 || type == 'hb'
    return
  end

  case chan['channel']
  when 'ticker'
    handle_ticker_message(msg, chan)
  when 'trades'
    handle_trades_message(msg, chan)
  when 'candles'
    handle_candles_message(msg, chan)
  when 'book'
    if type == 'cs'
      handle_order_book_checksum_message(msg, chan)
    else
      handle_order_book_message(msg, chan)
    end
  when 'auth'
    handle_auth_message(msg, chan)
  end
end

#process_event_message(msg) ⇒ Object

:nodoc:



489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
# File 'lib/ws/ws2.rb', line 489

def process_event_message (msg) # :nodoc:
  case msg['event']
  when 'auth'
    handle_auth_event(msg)
  when 'subscribed'
    handle_subscribed_event(msg)
  when 'unsubscribed'
    handle_unsubscribed_event(msg)
  when 'info'
    handle_info_event(msg)
  when 'conf'
    handle_config_event(msg)
  when 'error'
    handle_error_event(msg)
  end
end

#process_message(msg) ⇒ Object

:nodoc:



140
141
142
143
144
145
146
147
148
149
150
# File 'lib/ws/ws2.rb', line 140

def process_message (msg) # :nodoc:
  if @seq_audit
    validate_message_seq(msg)
  end

  if msg.kind_of?(Array)
    process_channel_message(msg)
  elsif msg.kind_of?(Hash)
    process_event_message(msg)
  end
end

#request_calc(prefixes) ⇒ Object

Requests a calculation to be performed

Parameters:

  • prefixes (Array)
    • i.e. [‘margin_base’]

See Also:



658
659
660
# File 'lib/ws/ws2.rb', line 658

def request_calc (prefixes)
  @ws.send(JSON.generate([0, 'calc', nil, prefixes.map { |p| [p] }]))
end

#sign(payload) ⇒ Object

:nodoc:



648
649
650
# File 'lib/ws/ws2.rb', line 648

def sign (payload) # :nodoc:
  OpenSSL::HMAC.hexdigest('sha384', @api_secret, payload)
end

#submit_order(order, &cb) ⇒ Object

Submit a new order

Parameters:

  • order (Hash|Array|Order)
  • cb (Block)
    • triggered upon receipt of confirmation notification



711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
# File 'lib/ws/ws2.rb', line 711

def submit_order (order, &cb)
  return if !@is_authenticated

  if order.kind_of?(Array)
    packet = order
  elsif order.instance_of?(Models::Order)
    packet = order.to_new_order_packet
  elsif order.kind_of?(Hash)
    packet = Models::Order.new(order).to_new_order_packet
  else
    raise Exception, 'tried to submit order of unkown type'
  end

  @ws.send(JSON.generate([0, 'on', nil, packet]))

  if packet.has_key?(:cid) && !cb.nil?
    @pending_blocks["order-new-#{packet[:cid]}"] = cb
  end
end

#subscribe(channel, params = {}) ⇒ Object

Subscribes to the specified channel; params dictate the channel filter

Parameters:

  • channel (string)
    • i.e. ‘trades’, ‘candles’, etc

  • params (Hash) (defaults to: {})
  • params.symbol (string?)
  • params.prec (string?)
    • for order book channels

  • params.len (string?)
    • for order book channels

  • params.key (string?)
    • for candle channels



439
440
441
442
443
444
445
# File 'lib/ws/ws2.rb', line 439

def subscribe (channel, params = {})
  @l.info 'subscribing to channel %s [%s]' % [channel, params]
  @ws.send(JSON.generate(params.merge({
    :event => 'subscribe',
    :channel => channel,
  })))
end

#subscribe_candles(key) ⇒ Object

Subscribes to a candle channel by key

Parameters:

  • key (string)
    • i.e. trade:1m:tBTCUSD



470
471
472
# File 'lib/ws/ws2.rb', line 470

def subscribe_candles (key)
  subscribe('candles', { :key => key })
end

#subscribe_order_book(sym, prec, len) ⇒ Object

Subscribes to an order book channel

Parameters:

  • sym (string)
    • i.e. tBTCUSD

  • prec (string)
    • i.e. R0, P0, etc

  • len (string)
    • i.e. 25, 100, etc



481
482
483
484
485
486
487
# File 'lib/ws/ws2.rb', line 481

def subscribe_order_book (sym, prec, len)
  subscribe('book', {
    :symbol => sym,
    :prec => prec,
    :len => len
  })
end

#subscribe_ticker(sym) ⇒ Object

Subscribes to a ticker channel by symbol

Parameters:

  • sym (string)
    • i.e. tBTCUSD



452
453
454
# File 'lib/ws/ws2.rb', line 452

def subscribe_ticker (sym)
  subscribe('ticker', { :symbol => sym })
end

#subscribe_trades(sym) ⇒ Object

Subscribes to a trades channel by symbol

Parameters:

  • sym (string)
    • i.e. tBTCUSD



461
462
463
# File 'lib/ws/ws2.rb', line 461

def subscribe_trades (sym)
  subscribe('trades', { :symbol => sym })
end

#update_order(changes, &cb) ⇒ Object

Update an order with a changeset by ID

Parameters:

  • changes (Hash)
    • must contain ID

  • cb (Block)
    • triggered upon receipt of confirmation notification



668
669
670
671
672
673
674
675
# File 'lib/ws/ws2.rb', line 668

def update_order (changes, &cb)
  id = changes[:id] || changes['id']
  @ws.send(JSON.generate([0, 'ou', nil, changes]))

  if !cb.nil?
    @pending_blocks["order-update-#{id}"] = cb
  end
end

#validate_message_seq(msg) ⇒ Object

:nodoc:



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
# File 'lib/ws/ws2.rb', line 152

def validate_message_seq (msg) # :nodoc:
  return unless @seq_audit
  return unless msg.kind_of?(Array)
  return unless msg.size > 2

  # The auth sequence # is the last value in channel 0 non-hb packets
  if msg[0] == 0 && msg[1] != 'hb'
    auth_seq = msg[-1]
  else
    auth_seq = nil
  end

  # all other packets provide a public sequence # as the last value. For
  # chan 0 packets, these are included as the 2nd to last value
  #
  # note that error notifications lack seq
  if msg[0] == 0 && msg[1] != 'hb' && !(msg[1] && msg[2][6] == 'ERROR')
    pub_seq = msg[-2]
  else
    pub_seq = msg[-1]
  end

  return unless pub_seq.is_a?(Numeric)

  if @last_pub_seq.nil?
    @last_pub_seq = pub_seq
    return
  end

  if pub_seq != (@last_pub_seq + 1) # check pub seq
    @l.warn "invalid pub seq #; last #{@last_pub_seq}, got #{pub_seq}"
  end

  @last_pub_seq = pub_seq

  return unless auth_seq.is_a?(Numeric)
  return if auth_seq == 0
  return if msg[1] == 'n' && msg[2][6] == 'ERROR' # error notifications
  return if auth_seq == @last_auth_seq # seq didn't advance

  if !@last_auth_seq.nil? && auth_seq != @last_auth_seq + 1
    @l.warn "invalid auth seq #; last #{@last_auth_seq}, got #{auth_seq}"
  end

  @last_auth_seq = auth_seq
end