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

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
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
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement