• This repository has been archived on 20/Jan/2020
  • Stars
    star
    122
  • Rank 292,031 (Top 6 %)
  • Language
    Ruby
  • License
    Apache License 2.0
  • Created over 9 years ago
  • Updated over 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,570
star
2

coinbase-wallet-sdk

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

coinbase-pro-trading-toolkit

DEPRECATED — The Coinbase Pro trading toolkit
TypeScript
864
star
4

kryptology

Go
846
star
5

coinbase-pro-node

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

build-onchain-apps

Accelerate your onchain creativity with the Build Onchain Apps Template. ⛵️
Solidity
701
star
7

odin

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

coinbase-python

DEPRECATED — Coinbase Python API
Python
521
star
9

onchainkit

React components and TypeScript utilities to help you build top-tier onchain apps.
TypeScript
481
star
10

solidity-style-guide

471
star
11

assume-role

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

geoengineer

DEPRECATED — Infrastructure As Code
Ruby
401
star
13

coinbase-node

DEPRECATED — The official Node.js library for the Coinbase API.
JavaScript
363
star
14

mesh-specifications

Specification files for the Mesh Blockchain Standard
Shell
320
star
15

cbpay-js

Coinbase Pay SDK
TypeScript
317
star
16

coinbase-php

DEPRECATED — PHP wrapper for the Coinbase API
PHP
297
star
17

smart-wallet

Solidity
287
star
18

coinbase-ruby

DEPRECATED — Ruby wrapper for the Coinbase API
Ruby
241
star
19

waas-sdk-react-native

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

temporal-ruby

Ruby SDK for Temporal
Ruby
218
star
21

step

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

wallet-mobile-sdk

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

mesh-sdk-go

Mesh Client Go SDK
Go
192
star
24

coinbase-ios-sdk

Integrate bitcoin into your iOS application with Coinbase
Swift
171
star
25

nft-dapp-starter-kit

Starter kit for developers who want to build an NFT minting site
TypeScript
159
star
26

mesh-cli

CLI for the Mesh API
Go
154
star
27

coinbase-java

Coinbase API v1 library for Java
Java
147
star
28

coinbase-commerce-node

Coinbase Commerce Node
JavaScript
142
star
29

waas-client-library-go

Coinbase Wallet as a Service (WaaS) Client Library in Go.
Go
140
star
30

coinbase-commerce-php

Coinbase Commerce PHP
PHP
136
star
31

traffic_jam

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

dexter

Forensics acquisition framework designed to be extensible and secure
Go
122
star
33

mongobetween

Go
110
star
34

multisig-tool

DEPRECATED — Multisig Vault recovery tool
JavaScript
110
star
35

mesh-bitcoin

Bitcoin Mesh API Implementation
Go
108
star
36

mesh-ethereum

Ethereum Mesh API Implementation
Go
100
star
37

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
98
star
38

coinbase-android-sdk

DEPRECATED — Android SDK for Coinbase
Java
96
star
39

react-coinbase-commerce

Coinbase Commerce React
JavaScript
92
star
40

fenrir

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

pwnbot

You call PwnBot in Slack on someone else's unlocked computer
JavaScript
90
star
42

commerce-onchain-payment-protocol

Solidity
90
star
43

digital-asset-policy-proposal

Digital Asset Policy Proposal: Safeguarding America’s Financial Leadership
84
star
44

coinbase-commerce-python

Coinbase Commerce Python
Python
79
star
45

magic-spend

Solidity
78
star
46

verifications

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

CBTabViewExample

TypeScript
72
star
48

chainstorage

The File System For a Multi-Blockchain World
Go
71
star
49

coinbase-bitmonet-sdk

DEPRECATED — Library to accept bitcoin payments in your Android App
Java
63
star
50

self-service-iam

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

coinbase-wordpress

DEPRECATED — Coinbase plugin/widget for Wordpress
57
star
52

coinbase-commerce-woocommerce

Accept Bitcoin on your WooCommerce-powered website.
PHP
57
star
53

paymaster-bundler-examples

JavaScript
55
star
54

barbar

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

demeter

DEPRECATED — Security Group Management For AWS
Ruby
52
star
56

coinbase-exchange-node

DEPRECATED — Use gdax-node
JavaScript
47
star
57

cadence-ruby

Ruby SDK for Cadence
Ruby
43
star
58

coinbase-woocommerce

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

protoc-gen-rbi

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

mesh-ecosystem

Repository of all open source Mesh implementations and SDKs
33
star
61

master_lock

Inter-process locking library using Redis.
Ruby
32
star
62

coinbase-commerce-ruby

Coinbase Commerce Ruby Gem
Ruby
30
star
63

watchdog

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

bittip

DEPRECATED — Reddit tip bot
JavaScript
27
star
65

cash-addr

Utility to convert between base58 and CashAddr BCH addresses.
Ruby
26
star
66

maxfuzz

DEPRECATED — Containerized Cloud Fuzzing
C
26
star
67

rules_ruby

Bazel Ruby Rules
Starlark
24
star
68

mesh-geth-sdk

go-ethereum based sdk for Mesh API
Go
24
star
69

onchain-app-template

TypeScript
24
star
70

redisbetween

Go
23
star
71

gtt-ui

DEPRECATED
JavaScript
22
star
72

btcexport

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

bchd-explorer

Vue
21
star
74

baseca

Go
21
star
75

coinbase-sdk-nodejs

TypeScript
21
star
76

coinbase-commerce-whmcs

Coinbase Commerce module for WHMCS
PHP
18
star
77

coinbase-nft-floor-price

Coinbase NFT floor price estimate model
Python
17
star
78

coinbase-magento

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

salus

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

coinbase-android-sdk-example

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

staking-client-library-go

Programmatic access to Coinbase's best-in-class staking infrastructure and services. 🔵
Go
15
star
82

coinbase-spree

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

coinbase-cloud-sdk-js

TypeScript
14
star
84

staking-client-library-ts

Programmatic access to Coinbase's best-in-class staking infrastructure and services. 🔵
TypeScript
14
star
85

service_variables

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

solidity-workshop

JavaScript
12
star
87

chainsformer

Go
12
star
88

omniauth-coinbase

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

coinbase-javascript-sdk

DEPRECATED
JavaScript
11
star
90

coinbase-commerce-prestashop

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

mkr-vote-proxy

Cold storage-friendly voting for MKR tokens
Solidity
11
star
92

chainnode

Go
10
star
93

step-asg-deployer

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

wrapped-tokens-os

TypeScript
10
star
95

eip-token-upgrade

Solidity
10
star
96

client-analytics

TypeScript
9
star
97

code-of-conduct

Code of conduct for open source projects managed by Coinbase
9
star
98

coinbase-magento2

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

coinbase-commerce-opencart

DEPRECATED — Coinbase Commerce Integration For Opencart
PHP
8
star
100

waas-proxy-server

Go
7
star