Skip to content

Instantly share code, notes, and snippets.

@jamilbk
Created July 25, 2019 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamilbk/27ee33f7a2ffc0329c6dde7d6c463fed to your computer and use it in GitHub Desktop.
Save jamilbk/27ee33f7a2ffc0329c6dde7d6c463fed to your computer and use it in GitHub Desktop.
Coinbase Pro REST API example in Elixir
defmodule CoinbasePro do
@moduledoc """
CoinbasePro exchange wrapper.
"""
@config Application.get_env(:config, __MODULE__)
@api_url (if Mix.env == :prod do
"https://api.pro.coinbase.com"
else
"https://api-public.sandbox.pro.coinbase.com"
end)
def api_url, do: @api_url
@req_headers [
{:"Content-Type", "application/json"},
{:Accept, "application/json"}
]
def place_order(payload) do
path = "/orders"
method = "POST"
url = "#{@api_url}#{path}"
ts = timestamp_str()
body = Jason.encode!(payload)
signature = build_signature(ts, path, method, body)
headers = Keyword.merge(auth_headers(signature, ts), @req_headers)
HTTPoison.request!(method, url, body, headers)
end
defp build_signature(timestamp, path, method, body) do
message = "#{timestamp}#{method}#{path}#{body}"
{:ok, decoded_secret} = Base.decode64(@config[:secret])
Base.encode64(:crypto.hmac(:sha256, decoded_secret, message))
end
defp auth_headers(signature, access_timestamp) do
[
{:"CB-ACCESS-KEY", @config[:access_key]},
{:"CB-ACCESS-SIGN", signature},
{:"CB-ACCESS-TIMESTAMP", access_timestamp},
{:"CB-ACCESS-PASSPHRASE", @config[:passphrase]}
]
end
defp timestamp_str do
Integer.to_string(:os.system_time(:seconds))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment