Created
December 19, 2018 19:51
-
-
Save alvises/c275004b878f22eda2b6f78cfbe2ce4a to your computer and use it in GitHub Desktop.
Realtime market-data updates - full channel - calculating the rate
This file contains 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
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