Skip to content

Instantly share code, notes, and snippets.

@alvises
Created December 19, 2018 19:51
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 alvises/c275004b878f22eda2b6f78cfbe2ce4a to your computer and use it in GitHub Desktop.
Save alvises/c275004b878f22eda2b6f78cfbe2ce4a to your computer and use it in GitHub Desktop.
Realtime market-data updates - full channel - calculating the rate
defmodule Coinbase.Client do
use WebSockex
@url "wss://ws-feed.pro.coinbase.com"
def start_link(products \\ []) do
{:ok, pid} = WebSockex.start_link(@url, __MODULE__, %{})
subscribe(pid, products)
{:ok, pid}
end
def handle_connect(_conn, state) do
IO.puts("connected!")
{:ok, state}
end
def handle_disconnect(_conn, state) do
IO.puts("disconnected")
{:ok, state}
end
def handle_frame({:text, msg}, state) do
handle_msg(Poison.decode!(msg), state)
end
def handle_msg(%{"time" => time}=event, seconds_counts) when is_binary(time) do
{:ok, time, _} = DateTime.from_iso8601(event["time"])
key = {time.year, time.month, time.day, time.hour, time.minute, time.second}
seconds_counts = Map.update(seconds_counts, key, 0, fn v -> v + 1 end)
{:ok, seconds_counts}
end
def handle_msg(_,state), do: {:ok,state}
def subscribe(pid, products) do
frame = subscription_frame(products)
WebSockex.send_frame(pid, frame)
end
defp subscription_frame(products) do
subscription_json =
%{
type: "subscribe",
product_ids: products,
channels: ["full"]
}
|> Poison.encode!()
{:text, subscription_json}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment