Module: Cryptum::API

Defined in:
lib/cryptum/api.rb

Overview

This plugin is used to interact withbtje Coinbase REST API

Class Method Summary collapse

Class Method Details

.cancel_all_open_orders(opts = {}) ⇒ Object

rest_api_call(

  env: env,
  http_method: :DELETE,
  api_call: "/orders/#{order_id}",
  option_choice: option_choice,
  params: params,
  order_type: order_type
)

rescue StandardError => e

raise e

end



435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/cryptum/api.rb', line 435

public_class_method def self.cancel_all_open_orders(opts = {})
  env = opts[:env]
  option_choice = opts[:option_choice]
  event_notes = opts[:event_notes]

  product_id = option_choice.symbol.to_s.gsub('_', '-').upcase

  order_hash = {}
  order_hash[:product_id] = product_id

  # http_body = order_hash.to_json
  params = order_hash

  canceled_order_id_arr = []
  loop do
    canceled_order_id_arr = rest_api_call(
      env: env,
      http_method: :DELETE,
      api_call: '/orders',
      option_choice: option_choice,
      params: params,
      event_notes: event_notes
    )

    break if canceled_order_id_arr.empty?
  end
  canceled_order_id_arr
rescue StandardError => e
  raise e
end

.generate_signature(opts = {}) ⇒ Object

Supported Method Parameters

Cryptum::API.generate_signature( )



16
17
18
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/cryptum/api.rb', line 16

public_class_method def self.generate_signature(opts = {})
  api_secret = opts[:api_secret]

  http_method = if opts[:http_method].nil?
                  :GET
                else
                  opts[:http_method].to_s.upcase.scrub.strip.chomp.to_sym
                end

  api_call = opts[:api_call].to_s.scrub.strip.chomp
  api_call = '/users/self/verify' if opts[:api_call].nil?

  if opts[:params].nil?
    path = api_call
  else
    uri = Addressable::URI.new
    uri.query_values = opts[:params]
    params = uri.query
    path = "#{api_call}?#{params}"
  end

  http_body = opts[:http_body].to_s.scrub.strip.chomp

  api_timestamp = Time.now.utc.to_i.to_s

  api_signature = Base64.strict_encode64(
    OpenSSL::HMAC.digest(
      'sha256',
      Base64.strict_decode64(api_secret),
      "#{api_timestamp}#{http_method}#{path}#{http_body}"
    )
  )

  if http_body == ''
    api_signature = Base64.strict_encode64(
      OpenSSL::HMAC.digest(
        'sha256',
        Base64.strict_decode64(api_secret),
        "#{api_timestamp}#{http_method}#{path}"
      )
    )
  end

  api_signature_response = {}
  api_signature_response[:api_timestamp] = api_timestamp
  api_signature_response[:api_signature] = api_signature

  api_signature_response
rescue RestClient::ExceptionWithResponse => e
  File.open('/tmp/cryptum-errors.txt', 'a') do |f|
    f.puts Time.now.strftime('%Y-%m-%d %H:%M:%S.%N %z')
    f.puts "Module: #{self}"
    f.puts "URL: #{api_endpoint}#{api_call}"
    f.puts "PARAMS: #{params.inspect}"
    f.puts "HTTP POST BODY: #{http_body.inspect}" if http_body != ''
    f.puts "#{e}\n#{e.response}\n\n\n"
  end
rescue StandardError => e
  raise e
end

.get_fees(opts = {}) ⇒ Object



570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'lib/cryptum/api.rb', line 570

public_class_method def self.get_fees(opts = {})
  option_choice = opts[:option_choice]
  env = opts[:env]

  fees_api_call = '/fees'

  # We don't always get fees back from Coinbase...
  # This is a hack to ensure we do.
  fees = {}
  fees = rest_api_call(
    option_choice: option_choice,
    env: env,
    http_method: :GET,
    api_call: fees_api_call
  )

  fees
rescue StandardError => e
  raise e
end

.get_order_history(opts = {}) ⇒ Object

profiles rescue StandardError => e

raise e

end



618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
# File 'lib/cryptum/api.rb', line 618

public_class_method def self.get_order_history(opts = {})
  option_choice = opts[:option_choice]
  env = opts[:env]

  product_id = option_choice.symbol.to_s.gsub('_', '-').upcase

  orders_api_call = '/orders'
  params = {}
  params[:product_id] = product_id
  params[:status] = 'all'

  # We don't always get order_history back from Coinbase...
  # This is a hack to ensure we do.
  order_history = []
  order_history = rest_api_call(
    option_choice: option_choice,
    env: env,
    http_method: :GET,
    api_call: orders_api_call,
    params: params
  )

  # Cast UTC Timestamps as local times
  order_history.each do |order|
    order[:created_at] = Time.parse(
      order[:created_at]
    ).localtime.to_s

    next unless order[:done_at]

    order[:done_at] = Time.parse(
      order[:done_at]
    ).localtime.to_s
  end

  order_history
rescue StandardError => e
  raise e
end

.get_portfolio(opts = {}) ⇒ Object



514
515
516
517
518
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
# File 'lib/cryptum/api.rb', line 514

public_class_method def self.get_portfolio(opts = {})
  option_choice = opts[:option_choice]
  env = opts[:env]
  crypto = opts[:crypto]
  fiat = opts[:fiat]
  fiat_portfolio_file = opts[:fiat_portfolio_file]
  event_notes = opts[:event_notes]

  # Retrieve Exchange Rates
  exchange_rates = get_exchange_rates(
    option_choice: option_choice,
    env: env
  )

  portfolio_complete_arr = []
  portfolio_complete_arr = rest_api_call(
    option_choice: option_choice,
    env: env,
    http_method: :GET,
    api_call: '/accounts',
    event_notes: event_notes
  )

  all_products = portfolio_complete_arr.select do |products|
    products if products[:balance].to_f.positive?
  end

  total_holdings = 0.00
  all_products.each do |product|
    currency = product[:currency].to_sym
    this_exchange_rate = exchange_rates[currency].to_f
    total_holdings += product[:balance].to_f / this_exchange_rate
  end

  crypto_portfolio = portfolio_complete_arr.select do |product|
    product if product[:currency] == crypto
  end

  fiat_portfolio = portfolio_complete_arr.select do |product|
    product if product[:currency] == fiat
  end
  fiat_portfolio.last[:total_holdings] = format(
    '%0.8f',
    total_holdings
  )

  File.write(
    fiat_portfolio_file,
    JSON.pretty_generate(fiat_portfolio)
  )

  crypto_portfolio
rescue StandardError => e
  raise e
end

.get_products(opts = {}) ⇒ Object



466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
# File 'lib/cryptum/api.rb', line 466

public_class_method def self.get_products(opts = {})
  option_choice = opts[:option_choice]
  env = opts[:env]

  products = rest_api_call(
    option_choice: option_choice,
    env: env,
    http_method: :GET,
    api_call: '/products'
  )

  if products.length.positive?
    supported_products_filter = products.select do |product|
      product[:id].match?(/USD$/) &&
        product[:status] == 'online' &&
        product[:fx_stablecoin] == false
    end
    sorted_products = supported_products_filter.sort_by { |hash| hash[:id] }
  end

  sorted_products
rescue StandardError => e
  raise e
end

.gtfo(opts = {}) ⇒ Object



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
358
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
# File 'lib/cryptum/api.rb', line 314

public_class_method def self.gtfo(opts = {})
  option_choice = opts[:option_choice]
  env = opts[:env]
  event_history = opts[:event_history]

  # Cancel all open orders
  cancel_all_open_orders(
    env: env,
    option_choice: option_choice
  )

  product_id = option_choice.symbol.to_s.gsub('_', '-').upcase

  this_product = event_history.order_book[:this_product]
  base_increment = this_product[:base_increment]
  quote_increment = this_product[:quote_increment]
  crypto_smallest_decimal = base_increment.to_s.split('.')[-1].length
  fiat_smallest_decimal = quote_increment.to_s.split('.')[-1].length

  # TODO: Calculate / Price / Size
  last_three_prices_arr = []
  last_ticker_price = event_history.order_book[:ticker_price].to_f
  second_to_last_ticker_price = event_history.order_book[:ticker_price_second_to_last].to_f
  third_to_last_ticker_price = event_history.order_book[:ticker_price_third_to_last].to_f
  last_three_prices_arr.push(last_ticker_price)
  last_three_prices_arr.push(second_to_last_ticker_price)
  last_three_prices_arr.push(third_to_last_ticker_price)
  limit_price = last_three_prices_arr.sort[1]
  price = format(
    "%0.#{fiat_smallest_decimal}f",
    limit_price
  )

  crypto_currency = option_choice.symbol.to_s.upcase.split('_').first.to_sym
  portfolio = event_history.order_book[:portfolio]
   = portfolio.select do ||
    [:currency] == crypto_currency.to_s
  end
  balance = format(
    "%0.#{crypto_smallest_decimal}f",
    .first[:balance]
  )

  current_crypto_fiat_value = format(
    '%0.2f',
    balance.to_f * price.to_f
  )

  order_hash = {}

  order_hash[:type] = 'limit'
  order_hash[:time_in_force] = 'GTT'
  order_hash[:cancel_after] = 'min'

  order_hash[:size] = balance
  order_hash[:price] = price
  order_hash[:side] = :sell
  order_hash[:product_id] = product_id

  http_body = order_hash.to_json

  limit_order_resp = rest_api_call(
    option_choice: option_choice,
    env: env,
    http_method: :POST,
    api_call: '/orders',
    http_body: http_body,
    base_increment: base_increment
  )

  # Populate Order ID on the Buy
  # to know what to do on the Sell
  this_order = {}
  this_order[:plan_no] = '0.0'
  this_order[:fiat_available] = '0.00'
  this_order[:risk_alloc] = current_crypto_fiat_value
  this_order[:allocation_decimal] = '1.0'
  this_order[:allocation_percent] = '100.0'
  this_order[:invest] = current_crypto_fiat_value
  this_order[:return] = current_crypto_fiat_value
  this_order[:profit] = '0.0'
  this_order[:buy_order_id] = 'N/A'
  this_order[:price] = price
  this_order[:tpm] = '0.00'
  this_order[:target_price] = current_crypto_fiat_value
  this_order[:size] = balance
  this_order[:color] = :magenta
  this_order[:sell_order_id] = limit_order_resp[:id]

  event_history.order_book[:order_history_meta].push(this_order)

  event_history
rescue StandardError => e
  raise e
end

.helpObject

Display Usage for this Module



660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
# File 'lib/cryptum/api.rb', line 660

public_class_method def self.help
  puts "USAGE:
   signature = #{self}.generate_signature(
     api_secret: 'required - Coinbase Pro API Secret',
     http_method: 'optional - Defaults to :GET',
     api_call: 'optional - Defaults to /users/self/verify',
     params: 'optional - HTTP GET Parameters',
     http_body: 'optional HTTP POST Body'
   )

   profiles = #{self}.get_profiles(
     env: 'required - Coinbase::Option.get_env Object'
   )

   products = #{self}.get_products(
     env: 'required - Coinbase::Option.get_env Object'
   )

   portfolio = #{self}.get_portfolio(
     env: 'required - Coinbase::Option.get_env Object'
   )

   order_history = #{self}.get_order_history(
     env: 'required - Coinbase::Option.get_env Object'
   )
  "
end

.submit_limit_order(opts = {}) ⇒ Object



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/cryptum/api.rb', line 231

public_class_method def self.submit_limit_order(opts = {})
  option_choice = opts[:option_choice]
  env = opts[:env]
  price = opts[:price]
  size = opts[:size]
  buy_or_sell = opts[:buy_or_sell]
  event_history = opts[:event_history]
  bot_conf = opts[:bot_conf]
  buy_order_id = opts[:buy_order_id]

  tpm = bot_conf[:target_profit_margin_percent].to_f
  tpm_cast_as_decimal = tpm / 100

  product_id = option_choice.symbol.to_s.gsub('_', '-').upcase

  this_product = event_history.order_book[:this_product]
  base_increment = this_product[:base_increment]
  quote_increment = this_product[:quote_increment]
  # crypto_smallest_decimal = base_increment.to_s.split('.')[-1].length
  fiat_smallest_decimal = quote_increment.to_s.split('.')[-1].length

  order_hash = {}

  order_hash[:type] = 'limit'
  order_hash[:time_in_force] = 'GTC'

  if buy_or_sell == :buy
    order_hash[:time_in_force] = 'GTT'
    order_hash[:cancel_after] = 'min'
  end

  order_hash[:size] = size
  order_hash[:price] = price
  order_hash[:side] = buy_or_sell
  order_hash[:product_id] = product_id

  http_body = order_hash.to_json

  limit_order_resp = rest_api_call(
    option_choice: option_choice,
    env: env,
    http_method: :POST,
    api_call: '/orders',
    http_body: http_body,
    base_increment: base_increment
  )

  # Populate Order ID on the Buy
  # to know what to do on the Sell
  case buy_or_sell
  when :buy
    this_order = event_history.order_book[:order_plan].shift
    this_order[:buy_order_id] = limit_order_resp[:id]
    this_order[:price] = price
    targ_price = price.to_f + (price.to_f * tpm_cast_as_decimal)
    this_order[:tpm] = format(
      '%0.2f',
      tpm
    )
    this_order[:target_price] = format(
      "%0.#{fiat_smallest_decimal}f",
      targ_price
    )

    this_order[:size] = size

    this_order[:color] = :cyan
    event_history.order_book[:order_history_meta].push(this_order)
  when :sell
    sell_order_id = limit_order_resp[:id]
    event_history.order_book[:order_history_meta].each do |meta|
      if meta[:buy_order_id] == buy_order_id
        meta[:sell_order_id] = sell_order_id
        meta[:color] = :yellow
      end
    end
  end

  event_history
rescue StandardError => e
  raise e
end