david234

david234

Arbitrage logic in Elixir

This is from my arbitrage project. I need to find the best probability of where the client can buy and where he can sell to get maximum profits. For ex take a look at the below list

[
  %{id: BTC, name: "Binance", price: 100},
  %{id: BTC, name: "VCC Exchange", price: 102},
  %{id: BTC, name: "CoinBene", price: 104},
  %{id: BTC, name: "BitZ", price: 140},
  %{id: BTC, name: "Huobi Global", price: 150},
  %{id: BTC, name: "ZG.com", price: 170},
]

Maximum Profit to Buy and Sell BTC:

1. BUY from ZG.com and SELL in Binance Profit 70
2. BUY from ZG.com and SELL in VCC Exchange Profit 68
3. BUY from ZG.com and SELL in CoinBene Profit 66
4. BUY from Huobi Global and SELL in Binance Profit 50
5. BUY from Huobi Global and SELL in VCC Exchange Profit 48
6. BUY from Huobi Global and SELL in CoinBene Profit 46
....
....
..

I have to find the best profits and list them.
So to achieve this what I have done is I have sorted the map based on Price ASC.
Then do I need to loop through each exchange 5 times in order to find this?
Or is there any better method of achieving this? Your help will be greatly appreciated.
Any skeleton code if I can get that will be really helpful.

Marked As Solved

amnu3387

amnu3387

Your example is giving the wrong values though, ZG would be the worse to buy since the price is highest there?

Because you need them all, ordered and not only the lowest and highest I would imagine a custom reduce would be the best option for doing it on almost a single pass.
I’ve added also other entries with the same prices to the sample list.

vals = [
  %{id: BTC, name: "Binance", price: 100},
  %{id: BTC, name: "VCC Exchange", price: 102},
  %{id: BTC, name: "CoinBene", price: 104},
  %{id: BTC, name: "CoinMale", price: 104},
  %{id: BTC, name: "BitZ", price: 140},
  %{id: BTC, name: "Huobi Global", price: 150},
  %{id: BTC, name: "Huobi Local", price: 150}, 
  %{id: BTC, name: "ZG.com", price: 170},
]

And a module for doing this:

defmodule Kombucha do

  def create(list_of_vals) do
    {mins, maxs, maps} = sort(list_of_vals)
    build_output(mins, maxs, maps)
  end

  def sort(list_of_vals) do
    list_of_vals
    |> Enum.reduce({[], [], %{}}, fn(%{name: name, price: price}, {mins, maxs, maps}) ->

      new_mins = add_min(price, mins)
      
      new_maxs = add_max(price, maxs)
      
      new_maps = Map.update(maps, price, [name], fn(existing) -> [name | existing] end)
      
      {new_mins, new_maxs, new_maps}
    end)
  end

  def add_max(price, rem, bigger \\ [])
  def add_max(price, [], bigger), do: :lists.flatten([bigger, price])
  def add_max(price, [h | t] = all, bigger) when price > h, do: :lists.flatten([bigger, price | all])
  def add_max(price, [price | t] = all, bigger), do: :lists.flatten([bigger | all])
  def add_max(price, [h | t], bigger), do: add_max(price, t, bigger ++ [h])

  def add_min(price, rem, smaller \\ [])
  def add_min(price, [], smaller), do: :lists.flatten([smaller, price])
  def add_min(price, [h | t] = all, smaller) when price < h, do: :lists.flatten([smaller, price | all])
  def add_min(price, [price | t] = all, smaller), do: :lists.flatten([smaller | all])
  def add_min(price, [h | t], smaller), do: add_min(price, t, smaller ++ [h])

  def build_output(mins, maxs, maps) do
    Enum.reduce(mins, [], fn(min, acc_1) ->
      Enum.reduce(maxs, acc_1, fn(max, acc_2) ->
        case min < max do
          true ->
            min_names = Map.get(maps, min)
            max_names = Map.get(maps, max)

            Enum.reduce(min_names, acc_2, fn(min_name, acc_3) ->
              Enum.reduce(max_names, acc_3, fn(max_name, acc_4) ->
                [%{buy: min_name, sell: max_name, profit: (max - min)} | acc_4]
              end)
            end)
          false -> acc_2
        end
      end)
    end)
    |> Enum.sort(fn(%{profit: profit_a}, %{profit: profit_b}) -> profit_a >= profit_b end)
  end
end

This should give you some ideas for how to tackle it. The build_out reductions could probably use reduce_while on the two outer reduces but it would clog up the logic and it doesn’t seem like it would be a significant improvement. You could also change it to keep adding entries to the output even if the profit was 0 or negative.

iex> Kombucha.create(vals) 
[
  %{buy: "Binance", profit: 70, sell: "ZG.com"},
  %{buy: "VCC Exchange", profit: 68, sell: "ZG.com"},
  %{buy: "CoinBene", profit: 66, sell: "ZG.com"},
  %{buy: "CoinMale", profit: 66, sell: "ZG.com"},
  %{buy: "Binance", profit: 50, sell: "Huobi Global"},
  %{buy: "Binance", profit: 50, sell: "Huobi Local"},
  %{buy: "VCC Exchange", profit: 48, sell: "Huobi Global"},
  %{buy: "VCC Exchange", profit: 48, sell: "Huobi Local"},
  %{buy: "CoinBene", profit: 46, sell: "Huobi Global"},
  %{buy: "CoinBene", profit: 46, sell: "Huobi Local"},
  %{buy: "CoinMale", profit: 46, sell: "Huobi Global"},
  %{buy: "CoinMale", profit: 46, sell: "Huobi Local"},
  %{buy: "Binance", profit: 40, sell: "BitZ"},
  %{buy: "VCC Exchange", profit: 38, sell: "BitZ"},
  %{buy: "CoinBene", profit: 36, sell: "BitZ"},
  %{buy: "CoinMale", profit: 36, sell: "BitZ"},
  %{buy: "BitZ", profit: 30, sell: "ZG.com"},
  %{buy: "Huobi Global", profit: 20, sell: "ZG.com"},
  %{buy: "Huobi Local", profit: 20, sell: "ZG.com"},
  %{buy: "BitZ", profit: 10, sell: "Huobi Global"},
  %{buy: "BitZ", profit: 10, sell: "Huobi Local"},
  %{buy: "Binance", profit: 4, sell: "CoinBene"},
  %{buy: "Binance", profit: 4, sell: "CoinMale"},
  %{buy: "VCC Exchange", profit: 2, sell: "CoinBene"},
  %{buy: "VCC Exchange", profit: 2, sell: "CoinMale"},
  %{buy: "Binance", profit: 2, sell: "VCC Exchange"}
]

Also Liked

kokolegorille

kokolegorille

oh, this look like a good fit to try Genetic Algorithms.

al2o3cr

al2o3cr

The core idea is to find each possible (buy, sell) pair, evaluate the profit, and then sort the results.

Here’s a way to do it in SQL (based on my solution to this year’s Advent of Code day 1):

WITH price_list (currency, market, price) AS (values
('BTC', 'Binance', 100),
('BTC', 'VCC Exchange', 102),
('BTC', 'CoinBene', 104),
('BTC', 'BitZ', 140),
('BTC', 'Huobi Global', 150),
('BTC', 'ZG.com', 170)
)
SELECT
price_list.currency,
price_list.market AS buy_market,
sell_price_list.market AS sell_market,
sell_price_list.price - price_list.price AS profit
FROM price_list
JOIN price_list AS sell_price_list
ON price_list.currency = sell_price_list.currency AND NOT (price_list.market = sell_price_list.market)
ORDER BY profit DESC

This gives the result:

 currency |  buy_market  | sell_market  | profit 
----------+--------------+--------------+--------
 BTC      | Binance      | ZG.com       |     70
 BTC      | VCC Exchange | ZG.com       |     68
 BTC      | CoinBene     | ZG.com       |     66
 BTC      | Binance      | Huobi Global |     50
 BTC      | VCC Exchange | Huobi Global |     48
 BTC      | CoinBene     | Huobi Global |     46
 BTC      | Binance      | BitZ         |     40
 BTC      | VCC Exchange | BitZ         |     38
 BTC      | CoinBene     | BitZ         |     36
 BTC      | BitZ         | ZG.com       |     30
 BTC      | Huobi Global | ZG.com       |     20
 BTC      | BitZ         | Huobi Global |     10
 BTC      | Binance      | CoinBene     |      4
 BTC      | Binance      | VCC Exchange |      2
 BTC      | VCC Exchange | CoinBene     |      2
 BTC      | VCC Exchange | Binance      |     -2
 BTC      | CoinBene     | VCC Exchange |     -2
 BTC      | CoinBene     | Binance      |     -4
 BTC      | Huobi Global | BitZ         |    -10
 BTC      | ZG.com       | Huobi Global |    -20
 BTC      | ZG.com       | BitZ         |    -30
 BTC      | BitZ         | CoinBene     |    -36
 BTC      | BitZ         | VCC Exchange |    -38
 BTC      | BitZ         | Binance      |    -40
 BTC      | Huobi Global | CoinBene     |    -46
 BTC      | Huobi Global | VCC Exchange |    -48
 BTC      | Huobi Global | Binance      |    -50
 BTC      | ZG.com       | CoinBene     |    -66
 BTC      | ZG.com       | VCC Exchange |    -68
 BTC      | ZG.com       | Binance      |    -70

My column labels don’t quite agree with yours, but you get the idea.

Note that this simple approach doesn’t scale particularly well: it evaluates every pair of buyers and sellers, so if you have N markets it takes N * (N-1) total calculations. Not bad when N=6, but not good when N=10000 :scream:

Where Next?

Popular in Questions Top

vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

Other popular topics Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

We're in Beta

About us Mission Statement