Skip to content

Instantly share code, notes, and snippets.

@tzumby
Last active February 6, 2019 02:00
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 tzumby/fce8b15b2c51e7bd7b65747ce4707e8c to your computer and use it in GitHub Desktop.
Save tzumby/fce8b15b2c51e7bd7b65747ce4707e8c to your computer and use it in GitHub Desktop.
Crypto Prices Module
defmodule CryptoPrices do
alias CryptoPrices.Aggregator
@clients [Aggregator.Bittrex, Aggregator.Poloniex, Aggregator.Kraken]
def compute(pair, opts \\ []) do
timeout = opts[:timeout] || 2_000
opts = Keyword.put_new(opts, :limit, 10)
clients = opts[:clients] || @clients
clients
|> Enum.map(&async_query(&1, pair, opts))
|> Task.yield_many(timeout)
|> Enum.map(fn {task, res} -> res || Task.shutdown(task, :brutal_kill) end)
|> Enum.flat_map(fn
{:ok, results } -> results
_ -> []
end)
|> Enum.reduce({0,0}, &avg/2)
|> avg_finalize
end
defp avg(x, {sum, count}), do: {sum + x.price, count + 1}
defp avg_finalize({sum, count}), do: sum / c
defp async_query(client, pair, opts) do
Task.Supervisor.async_nolink(Aggregator.TaskSupervisor,
client, :compute, [pair, opts], shutdown: :brutal_kill
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment