Last active
April 26, 2025 10:32
-
-
Save TimothyClayton/1ae505cb576528e89fe32b1b74098121 to your computer and use it in GitHub Desktop.
Coinbase Advanced Trade v3 REST API Ruby Client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "uri" | |
require "json" | |
require "net/http" | |
class Client | |
API_KEY = ENV['API_KEY'] | |
API_SECRET = ENV['API_SECRET'] | |
BASE_URL = 'https://api.coinbase.com' | |
BASE_PATH = '/api/v3/brokerage' | |
PRODUCT_ID = BotSettings::PRODUCT_ID | |
THROTTLE_MIN = BotSettings::THROTTLE_MIN | |
class << self | |
def quote | |
args = { | |
method: 'GET', | |
endpoint: "/products/#{PRODUCT_ID}/ticker", | |
query_params: '?limit=1' | |
} | |
request(**args) | |
end | |
def open_orders | |
args = { | |
method: 'GET', | |
endpoint: '/orders/historical/batch', | |
query_params: "?product_id=#{PRODUCT_ID}&order_status=OPEN" | |
} | |
request(**args) | |
end | |
def accounts | |
args = { | |
method: 'GET', | |
endpoint: '/accounts', | |
} | |
request(**args) | |
end | |
def products | |
args = { | |
method: 'GET', | |
endpoint: '/products', | |
} | |
request(**args) | |
end | |
def cancel_orders(order_ids) | |
args = { | |
method: 'POST', | |
endpoint: '/orders/batch_cancel', | |
body: { | |
order_ids: order_ids | |
}.to_json | |
} | |
request(**args) | |
end | |
def limit_order(size, price, side) | |
args = { | |
method: 'POST', | |
endpoint: '/orders', | |
body: { | |
'order_configuration': { | |
'limit_limit_gtc': { | |
'base_size': size, | |
'limit_price': price | |
} | |
}, | |
'client_order_id': SecureRandom.urlsafe_base64, | |
'product_id': PRODUCT_ID, | |
'side': side | |
}.to_json | |
} | |
request(**args) | |
end | |
end | |
def self.request(method:, endpoint:, query_params: '', body: '') | |
url = URI(BASE_URL + BASE_PATH + endpoint + query_params) | |
request_path = BASE_PATH + endpoint | |
timestamp = Time.now.to_i | |
payload = "#{timestamp}#{method}#{request_path}#{body}" | |
signature = OpenSSL::HMAC.hexdigest('sha256', API_SECRET, payload) | |
http = Net::HTTP.new(url.host, url.port) | |
http.use_ssl = true | |
if method == 'GET' | |
request = Net::HTTP::Get.new(url) | |
else | |
request = Net::HTTP::Post.new(url) | |
request.body = body | |
end | |
request["accept"] = 'application/json' | |
request["CB-ACCESS-KEY"] = API_KEY | |
request["CB-ACCESS-SIGN"] = signature | |
request["CB-ACCESS-TIMESTAMP"] = timestamp | |
response = http.request(request) | |
response.read_body | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment