• This repository has been archived on 20/Jan/2020
  • Stars
    star
    122
  • Rank 281,471 (Top 6 %)
  • Language
    Ruby
  • License
    Apache License 2.0
  • Created almost 9 years ago
  • Updated almost 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

DEPRECATED — Official Ruby library for the GDAX API

Coinbase Pro Ruby library

Note: This library isn't actively maintained. Please refer to the Node.js client library for an up-to-date client implementation.

REST Client

We provide an exchange client that is a thin wrapper over the exchange API. The purpose of this Readme is to provide context for using the gem effectively. For a detailed overview of the information that's available through the API, we recommend consulting the official documentation.

We provide a synchronous and asynchronous client. The only functional difference between the two clients is that the asynchronous client must be started inside the Eventmachine reactor loop.

Synchronous Client

require 'coinbase/exchange'

rest_api = Coinbase::Exchange::Client.new(api_key, api_secret, api_pass)
while true
  sleep 10
  rest_api.last_trade(product_id: "BTC-GBP") do |resp|
    p "Spot Rate: £ %.2f" % resp.price
  end
end

Asynchronous Client

require 'coinbase/exchange'
require 'eventmachine'

rest_api = Coinbase::Exchange::AsyncClient.new(api_key, api_secret, api_pass)
EM.run {
  EM.add_periodic_timer(10) {
    rest_api.last_trade(product_id: "BTC-GBP") do |resp|
      p "Spot Rate: £ %.2f" % resp.price
    end
  }
}

Usage

Installation

$ gem install coinbase-exchange

Initialization

To initialize the client, simply pass in an API Key, API Secret, and API Passphrase which you generate on the web interface:

rest_api = Coinbase::Exchange::Client.new(api_key, api_secret, api_pass)
rest_api = Coinbase::Exchange::AsyncClient.new(api_key, api_secret, api_pass)

Default Product

Coinbase Pro supports trading bitcoin in several currencies. If you wish to trade a different currency, you can specify an alternative default currency.

gbp_client = Coinbase::Exchange::Client.new(api_key, api_secret, api_pass,
                                            product_id: "BTC-GBP")

Sandbox

You can initialize a connection to the sandbox by specifying an alternative api endpoint.

sandbox = Coinbase::Exchange::Client.new(api_key, api_secret, api_pass,
                                          api_url: "https://api-public.sandbox.pro.coinbase.com")

Methods

The default representation of return data is an unmodified hash from the JSON blob returned in the body of the API response. The response should be accessed in a block like this.

rest_api.last_trade do |resp|
  p "Spot Rate: $ %.2f" % BigDecimal(resp['price'])
end

Note, the synchronous client will also return the same data. However, this is discouraged since it will make porting code to an asynchronous client more difficult. Here is an example of what that might look like.

resp = rest_api.last_trade
p "Spot Rate: $ %.2f" % BigDecimal(resp['price'])

Parameters

The gem will automatically encode any additional parameters you pass to method calls. For instance to get the full orderbook, you must explicitly set the level parameter to 3.

rest_api.orderbook(level: 3) do |resp|
  p "There are #{resp['bids'].count} open bids on the orderbook"
  p "There are #{resp['asks'].count} open asks on the orderbook"
end

Return Values

Data format is a sensitive issue when writing financial software. The exchange API represents monetary data in string format. This is a good intermediary data format for the user to apply their own data format, but is not especially useful on its own.

For representing monetary data in ruby, we recommend using the [BigDecimal] (http://ruby-doc.org/stdlib-2.1.1/libdoc/bigdecimal/rdoc/BigDecimal.html) library. If you access data by calling response items as though they were methods on the response itself. If you access data this way, any numerical data will be converted to BigDecimal format.

rest_api.orders(before: Time.now - 60*60) do |resp|
  resp.each do |order|
    p sprintf "#{order.side} ฿ %.8f for $ %.2f", order.size, order.price
  end
end

Errors

The gem will throw an error if it detects an exception. The possible errors are:

Error Description
APIError Parent class for all errors.
BadRequestError Server returned status 400.
NotAuthorizedError Server returned status 401.
ForbiddenError Server returned status 403.
NotFoundError Server returned status 404.
RateLimitError Server returned status 429.
InternalServerError Server returned status 500.

Metadata

You may need more fine-grained access to API response than just the body. We additionally provide access to the response headers, status, and the raw response as represented by the underlying library.

rest_api.last_trade do |resp|
  p "Status: #{resp.response_status}"
  p "Headers: #{resp.response_headers}"
  p "Response: #{resp.raw}"
end

Endpoints

[Market Data] (https://docs.pro.coinbase.com/#market-data)

Coinbase supports trading in multiple currencies. When interacting with market data, you can get information about a product other than your default by setting the product_id parameter.

rest_api.last_trade(product_id: 'BTC-GBP') do |resp|
  p "The spot rate is £ %.2f" % resp.price
end

currencies

Fetches a list of currencies we support.

rest_api.currencies do |resp|
  resp.each do |currency|
    p "The symbol for #{currency.name} is #{currency.id}"
  end
end

products

Fetches a list of products we offer.

rest_api.products do |resp|
  resp.each do |product|
    p "The most #{product.base_currency} you can buy with #{product.quote_currency} is %f" % product.base_max_size
  end
end

orderbook

Downloads a list of all open orders on our exchange.

rest_api.orderbook do |resp|
  p resp
end

If you wish to download a level 2 or level 3 orderbook, pass a level parameter to the method.

rest_api.orderbook(level: 3) do |resp|
  p "There are #{resp.bids.count} open bids on the orderbook"
  p "There are #{resp.asks.count} open asks on the orderbook"
end

last_trade

Downloads information about the last trade, which is exposed through the /ticker endpoint.

rest_api.last_trade do |resp|
  p "The spot rate is $ %.2f" %  resp.price
end

trade_history

Downloads recent trades. Please be aware that if you don't explicitly pass a before parameter this will recursively download every trade that's ever been placed.

rest_api.trade_history(before: Time.now - 10*60) do |resp|
  p "#{resp.count} trades have occurred in the past 10 minutes."
end

price_history

Downloads price history. We recommend setting a start parameter. You may also find the granularity parameter useful.

rest_api.price_history(start: Time.now - 60*60, granularity: 60) do |resp|
  p "In the past hour, the maximum price movement was $ %.2f" % resp.map { |candle| candle.high - candle.low }.max
end

daily_stats

Downloads price information over the past 24 hours.

rest_api.daily_stats do |resp|
  p "The highest price in in the past 24 hours was %.2f" % resp.high
  p "The lowest price in in the past 24 hours was %.2f" % resp.low
end

[Accounts] (https://docs.pro.coinbase.com/#accounts)

accounts

Downloads information about your accounts.

rest_api.accounts do |resp|
  resp.each do |account|
    p "#{account.id}: %.2f #{account.currency} available for trading" % account.available
  end
end

account

Downloads information about a single account. You must pass the account id as the first parameter.

rest_api.account(account_id) do |account|
  p "Account balance is %.2f #{account.currency}" % account.balance
end

account_history

Downloads a ledger of transfers, matches, and fees associated with an account. You must pass the account id as the first parameter.

rest_api.account_history(account_id) do |resp|
  p resp
end

account_holds

Holds are placed on an account for open orders. This will download a list of all account holds.

rest_api.account_holds(account_id) do |resp|
  p resp
end

[Orders] (https://docs.pro.coinbase.com/#orders)

bid

Places a buy order. Required parameters are amount and price.

rest_api.bid(0.25, 250) do |resp|
  p "Order ID is #{resp.id}"
end

buy

This is an alias for bid.

rest_api.buy(0.25, 250) do |resp|
  p "Order ID is #{resp.id}"
end

ask

Places a sell order. Required parameters are amount and price.

rest_api.ask(0.25, 250) do |resp|
  p "Order ID is #{resp.id}"
end

sell

This is an alias for ask.

rest_api.sell(0.25, 250) do |resp|
  p "Order ID is #{resp.id}"
end

cancel

Cancels an order. This returns no body, but you can still pass a block to execute on a successful return.

rest_api.cancel(order_id) do
  p "Order canceled successfully"
end

orders

Downloads a list of all your orders. Most likely, you'll only care about your open orders when using this.

rest_api.orders(status: "open") do |resp|
  p "You have #{resp.count} open orders."
end

order

Downloads information about a single order.

rest_api.order(order_id) do |resp|
  p "Order status is #{resp.status}"
end

fills

Downloads a list of fills.

rest_api.fills do |resp|
  p resp
end

[Transfers] (https://docs.pro.coinbase.com/#transfer-funds)

deposit

Deposit money from a Coinbase wallet.

rest_api.deposit(wallet_id, 10) do |resp|
  p "Deposited 10 BTC"
end

withdraw

Withdraw money for your Coinbase wallet.

rest_api.withdraw(wallet_id, 10) do |resp|
  p "Withdrew 10 BTC"
end

Other

server_time

Download the server time.

rest_api.server_time do |resp|
  p "The time on the server is #{resp}"
end

Websocket Client

We recommend reading the official websocket documentation before proceeding.

We provide a websocket interface in the gem for convenience. This is typically used to build a real-time orderbook, although it can also be used for simpler purposes such as tracking the market rate, or tracking when your orders fill. Like the asynchronous client, this depends Eventmachine for asynchronous processing.

Please consider setting the keepalive flag to true when initializing the websocket. This will cause the websocket to proactively refresh the connection whenever it closes.

websocket = Coinbase::Exchange::Websocket.new(keepalive: true)

Before starting the websocket, you should hook into whatever messages you're interested in by passing a block to the corresponding method. The methods you can use for access are open, match, change, done, and error. Additionally, you can use message to run a block on every websocket event.

require 'coinbase/exchange'
require 'eventmachine'

websocket = Coinbase::Exchange::Websocket.new(product_id: 'BTC-GBP',
                                              keepalive: true)
websocket.match do |resp|
  p "Spot Rate: £ %.2f" % resp.price
end

EM.run do
  websocket.start!
  EM.add_periodic_timer(1) {
    websocket.ping do
      p "Websocket is alive"
    end
  }
  EM.error_handler { |e|
    p "Websocket Error: #{e.message}"
  }
end

If started outside the reactor loop, the websocket client will use a very basic Eventmachine handler.

require 'coinbase/exchange'

websocket = Coinbase::Exchange::Websocket.new(product_id: 'BTC-GBP')
websocket.match do |resp|
  p "Spot Rate: £ %.2f" % resp.price
end
websocket.start!

More Repositories

1

terraform-landscape

Improve Terraform's plan output to be easier to read and understand
Ruby
1,546
star
2

coinbase-wallet-sdk

An open protocol that lets users connect their mobile wallets to your DApp
TypeScript
1,276
star
3

coinbase-pro-trading-toolkit

DEPRECATED — The Coinbase Pro trading toolkit
TypeScript
856
star
4

kryptology

Go
838
star
5

coinbase-pro-node

DEPRECATED — The official Node.js library for Coinbase Pro
JavaScript
828
star
6

build-onchain-apps

Accelerate your web3 creativity with the Build Onchain Apps Toolkit. ⛵️
TypeScript
570
star
7

odin

Archived: Odin deployer to AWS for 12 Factor applications.
Go
540
star
8

coinbase-python

DEPRECATED — Coinbase Python API
Python
511
star
9

assume-role

DEPRECATED — assume-role: a CLI tool making it easy to assume IAM roles through an AWS Bastion account
Shell
424
star
10

geoengineer

DEPRECATED — Infrastructure As Code
Ruby
403
star
11

coinbase-node

DEPRECATED — The official Node.js library for the Coinbase API.
JavaScript
361
star
12

mesh-specifications

Specification files for the Rosetta Blockchain Standard
Shell
313
star
13

coinbase-php

DEPRECATED — PHP wrapper for the Coinbase API
PHP
293
star
14

onchainkit

React components and TypeScript utilities for top-tier onchain apps.
TypeScript
287
star
15

cbpay-js

Coinbase Pay SDK
TypeScript
270
star
16

coinbase-ruby

DEPRECATED — Ruby wrapper for the Coinbase API
Ruby
239
star
17

waas-sdk-react-native

Coinbase Wallet as a Service (WaaS) SDK for React Native. Enables MPC Operations for iOS and Android Devices.
TypeScript
222
star
18

step

step is a framework for building, testing and deploying AWS Step Functions and Lambda
Go
207
star
19

wallet-mobile-sdk

An open protocol for mobile web3 apps to interact with wallets
Kotlin
203
star
20

temporal-ruby

Ruby SDK for Temporal
Ruby
194
star
21

mesh-sdk-go

Rosetta Client Go SDK
Go
182
star
22

coinbase-ios-sdk

Integrate bitcoin into your iOS application with Coinbase
Swift
172
star
23

nft-dapp-starter-kit

Starter kit for developers who want to build an NFT minting site
TypeScript
153
star
24

coinbase-java

Coinbase API v1 library for Java
Java
146
star
25

coinbase-commerce-node

Coinbase Commerce Node
JavaScript
143
star
26

mesh-cli

CLI for the Rosetta API
Go
142
star
27

waas-client-library-go

Coinbase Wallet as a Service (WaaS) Client Library in Go.
Go
138
star
28

traffic_jam

DEPRECATED — Ruby library for time-based rate limiting
Ruby
129
star
29

coinbase-commerce-php

Coinbase Commerce PHP
PHP
127
star
30

dexter

Forensics acquisition framework designed to be extensible and secure
Go
118
star
31

multisig-tool

DEPRECATED — Multisig Vault recovery tool
JavaScript
110
star
32

mesh-bitcoin

Bitcoin Rosetta API Implementation
Go
104
star
33

smart-wallet

Solidity
103
star
34

mesh-ethereum

Ethereum Rosetta API Implementation
Go
98
star
35

coinbase-android-sdk

DEPRECATED — Android SDK for Coinbase
Java
95
star
36

mongobetween

Go
93
star
37

fenrir

Archived: AWS SAM deployer to manage serverless projects.
Go
91
star
38

react-coinbase-commerce

Coinbase Commerce React
JavaScript
91
star
39

pwnbot

You call PwnBot in Slack on someone else's unlocked computer
JavaScript
89
star
40

digital-asset-policy-proposal

Digital Asset Policy Proposal: Safeguarding America’s Financial Leadership
85
star
41

coinbase-commerce-python

Coinbase Commerce Python
Python
77
star
42

CBTabViewExample

TypeScript
69
star
43

coinbase-bitmonet-sdk

DEPRECATED — Library to accept bitcoin payments in your Android App
Java
62
star
44

chainstorage

The File System For a Multi-Blockchain World
Go
61
star
45

self-service-iam

DEPRECATED — Self Service AWS IAM Policies for dev at scale
JavaScript
58
star
46

coinbase-wordpress

DEPRECATED — Coinbase plugin/widget for Wordpress
57
star
47

coinbase-commerce-woocommerce

Accept Bitcoin on your WooCommerce-powered website.
PHP
55
star
48

barbar

DEPRECATED — OSX crypto-currency price ticker
Swift
53
star
49

demeter

DEPRECATED — Security Group Management For AWS
Ruby
52
star
50

verifications

📜 "Coinbase Verifications" is a set of Coinbase-verified onchain attestations that enable access to apps and other onchain benefits.
Solidity
50
star
51

coinbase-exchange-node

DEPRECATED — Use gdax-node
JavaScript
46
star
52

cadence-ruby

Ruby SDK for Cadence
Ruby
44
star
53

commerce-onchain-payment-protocol

Solidity
41
star
54

protoc-gen-rbi

Protobuf compiler plugin that generates Sorbet .rbi "Ruby Interface" files.
Go
38
star
55

coinbase-woocommerce

DEPRECATED — Accept Bitcoin on your WooCommerce-powered website.
38
star
56

coinbase-advanced-py

The Advanced API Python SDK is a Python package that makes it easy to interact with the Coinbase Advanced API. The SDK handles authentication, HTTP connections, and provides helpful methods for interacting with the API.
Python
37
star
57

mesh-ecosystem

Repository of all open source Rosetta implementations and SDKs
33
star
58

master_lock

Inter-process locking library using Redis.
Ruby
31
star
59

coinbase-commerce-ruby

Coinbase Commerce Ruby Gem
Ruby
30
star
60

watchdog

DEPRECATED -- Github Bot for Datadog codification
Go
28
star
61

bittip

DEPRECATED — Reddit tip bot
JavaScript
27
star
62

maxfuzz

DEPRECATED — Containerized Cloud Fuzzing
C
26
star
63

cash-addr

Utility to convert between base58 and CashAddr BCH addresses.
Ruby
25
star
64

rules_ruby

Bazel Ruby Rules
Starlark
24
star
65

mesh-geth-sdk

go-ethereum based sdk for Rosetta API
Go
23
star
66

gtt-ui

DEPRECATED
JavaScript
22
star
67

btcexport

Export process for Bitcoin blockchain data to CSV
Go
22
star
68

bchd-explorer

Vue
21
star
69

redisbetween

Go
20
star
70

baseca

Go
18
star
71

coinbase-magento

DEPRECATED — Accept Bitcoin on your Magento-powered website.
17
star
72

coinbase-commerce-whmcs

Coinbase Commerce module for WHMCS
PHP
16
star
73

coinbase-android-sdk-example

DEPRECATED — Example android app leveraging the coinbase android sdk
Java
15
star
74

coinbase-nft-floor-price

Coinbase NFT floor price estimate model
Python
15
star
75

coinbase-spree

DEPRECATED — Accept bitcoin payments on your Spree store with Coinbase.
15
star
76

service_variables

Service level variables backed by Redis - useful for service wide configuration.
Ruby
12
star
77

solidity-workshop

JavaScript
12
star
78

omniauth-coinbase

DEPRECATED — Coinbase OAuth 2 Strategy for Omniauth
Ruby
12
star
79

coinbase-javascript-sdk

DEPRECATED
JavaScript
11
star
80

coinbase-commerce-prestashop

DEPRECATED — Official Coinbase Commerce Prestashop Payment Module
PHP
11
star
81

wrapped-tokens-os

TypeScript
11
star
82

coinbase-cloud-sdk-js

TypeScript
11
star
83

step-asg-deployer

Deprecated, renamed and maintained at https://github.com/coinbase/odin
Go
10
star
84

eip-token-upgrade

Solidity
10
star
85

mkr-vote-proxy

Cold storage-friendly voting for MKR tokens
Solidity
10
star
86

salus

We would like to request that all contributors please clone a *fresh copy* of this repository since the September 21st maintenance.
HTML
9
star
87

chainsformer

Go
9
star
88

coinbase-magento2

DEPRECATED: Accept Bitcoin on your Magento2-powered website.
8
star
89

code-of-conduct

Code of conduct for open source projects managed by Coinbase
8
star
90

coinbase-commerce-opencart

DEPRECATED — Coinbase Commerce Integration For Opencart
PHP
8
star
91

magic-spend

Solidity
8
star
92

chainnode

Go
7
star
93

waas-proxy-server

Go
7
star
94

client-analytics

TypeScript
7
star
95

node-process-lock

DEPRECATED — Simple process locking using Redis.
JavaScript
7
star
96

coinbase-commerce-magento

DEPRECATED — Coinbase Commerce Payment Gateway For Magento 2
PHP
7
star
97

coinbase-commerce-gravity-forms

DEPRECATED — Official Coinbase Commerce Payment Gateway For Gravity Forms
PHP
7
star
98

paymaster-bundler-examples

7
star
99

coinbase-zencart

DEPRECATED — Accept Bitcoin on your Zen Cart-powered website.
6
star
100

demeter-example

DEPRECATED — Demeter
6
star