Last active
February 6, 2019 02:00
-
-
Save tzumby/fce8b15b2c51e7bd7b65747ce4707e8c to your computer and use it in GitHub Desktop.
Crypto Prices Module
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 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