Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
crypto_arbitrage_example.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31
85# include <cmath>
86# include <iomanip>
87# include <iostream>
88# include <string>
89# include <utility>
90
91# include <Min_Mean_Cycle.H>
92# include <Negative_Cycles.H>
93# include <tpl_array.H>
94# include <tpl_dynMapTree.H>
95# include <tpl_graph.H>
96
97using namespace std;
98using namespace Aleph;
99
100namespace
101{
104 using Asset = Market::Node;
105 using Trade = Market::Arc;
106
108 constexpr double trading_fee = 0.001;
109
118 struct Log_Rate_Distance
119 {
120 using Distance_Type = double;
121
122 double fee = trading_fee;
123 double margin = 0.0;
124
130 double operator()(Trade * trade) const
131 {
132 return -std::log(trade->get_info() * (1.0 - fee)) + margin;
133 }
134 };
135
138 struct Pair
139 {
140 const char * base;
141 const char * quote;
142 double distortion;
143 };
144
146 double usdt_value(const string & asset)
147 {
148 if (asset == "BTC")
149 return 60000.0;
150 if (asset == "ETH")
151 return 3000.0;
152 if (asset == "BNB")
153 return 600.0;
154 if (asset == "SOL")
155 return 150.0;
156 if (asset == "ADA")
157 return 0.5;
158 return 1.0; // USDT
159 }
160
168 const Pair pairs[] =
169 {
170 {"BTC", "USDT", 0.0},
171 {"ETH", "USDT", 0.0},
172 {"ETH", "BTC", 0.010}, // ETH is 1.0 % too expensive in BTC
173 {"BNB", "USDT", 0.0},
174 {"SOL", "USDT", 0.0},
175 {"SOL", "BNB", 0.0},
176 {"ADA", "USDT", 0.0},
177 {"ADA", "SOL", 0.0},
178 {"ADA", "BNB", 0.008}, // ADA is 0.8 % too expensive in BNB
179 {"BNB", "BTC", 0.0},
180 };
181
185 void build_market(Market & market)
186 {
188 auto asset_of = [&](const char * name) -> Asset *
189 {
190 const string key = name;
191 if (not assets.has(key))
192 assets.insert(key, market.insert_node(key));
193 return assets.find(key);
194 };
195
196 for (const Pair & p : pairs)
197 {
198 const double price = usdt_value(p.base) / usdt_value(p.quote) * (1.0 + p.distortion);
199 Asset * base = asset_of(p.base);
200 Asset * quote = asset_of(p.quote);
201 market.insert_arc(quote, base, 1.0 / price); // buy the base
202 market.insert_arc(base, quote, price); // sell the base
203 }
204 }
205
208 struct Opportunity
209 {
210 string route;
211 size_t trades = 0;
212 double gain = 0.0;
213 };
214
225 Opportunity describe(const DynList<Asset *> & assets, const DynList<Trade *> & trades)
226 {
227 Array<string> names;
228 assets.for_each([&names](Asset * a) { names.append(a->get_info()); });
229 (void) names.remove_last(); // drop the repeated first asset
230
231 size_t first = 0;
232 for (size_t i = 1; i < names.size(); ++i)
233 if (names(i) < names(first))
234 first = i;
235
236 Opportunity op;
237 for (size_t i = 0; i < names.size(); ++i)
238 op.route += names((first + i) % names.size()) + " -> ";
239 op.route += names(first);
240 op.trades = names.size();
241
242 double growth = 1.0;
243 trades.for_each([&growth](Trade * t) { growth *= t->get_info() * (1.0 - trading_fee); });
244 op.gain = growth - 1.0;
245 return op;
246 }
247
248 void print_opportunity(const Opportunity & op)
249 {
250 cout << " " << op.route << " (" << op.trades << " trades, gain "
251 << showpos << fixed << setprecision(3) << op.gain * 100.0 << "%" << noshowpos << ")\n";
252 }
253
256 size_t list_opportunities(const Market & market, const double margin, const size_t max_cycles)
257 {
258 const auto cycles = find_disjoint_negative_cycles(
259 market, max_cycles, Negative_Cycle_Exclusion::All_Arcs,
260 Log_Rate_Distance{trading_fee, margin});
261
262 Array<Opportunity> found;
263 for (auto it = cycles.get_it(); it.has_curr(); it.next_ne())
264 found.append(describe(it.get_curr().cycle.nodes(), it.get_curr().cycle.arcs()));
265
266 // At most a handful of items: a plain insertion sort, best gain first.
267 for (size_t i = 1; i < found.size(); ++i)
268 for (size_t j = i; j > 0 and found(j).gain > found(j - 1).gain; --j)
269 swap(found(j), found(j - 1));
270
271 for (size_t i = 0; i < found.size(); ++i)
272 print_opportunity(found(i));
273 return found.size();
274 }
275
276 void show_bounded(const Market & market, const size_t max_trades)
277 {
278 const auto r = most_negative_cycle_bounded(market, max_trades,
279 Log_Rate_Distance{trading_fee, 0.0});
280 cout << " at most " << max_trades << " trades: ";
281 if (not r.is_negative())
282 {
283 cout << "no profitable cycle\n";
284 return;
285 }
286
287 // With floating-point weights a proof of optimality (`is_exact`) is rare,
288 // because the search rounds; `optimality_gap` bounds rigorously how much
289 // better (in log terms) the best cycle of the bound can be.
290 const Opportunity op = describe(r.cycle_nodes, r.cycle_arcs);
291 cout << op.route << " (gain " << showpos << fixed << setprecision(3) << op.gain * 100.0
292 << "%" << noshowpos << ", ";
293 if (r.is_exact)
294 cout << "proven optimal";
295 else
296 cout << "within " << scientific << setprecision(0) << r.optimality_gap
297 << " of the best in log terms, a rigorous bound" << fixed;
298 cout << ")\n";
299 }
300} // namespace
301
302
303int main()
304{
305 Market market;
306 build_market(market);
307
308 cout << "Crypto arbitrage reference example\n";
309 cout << "Market: " << market.get_num_nodes() << " assets, "
310 << market.get_num_arcs() / 2 << " pairs, fee " << fixed << setprecision(2)
311 << trading_fee * 100.0 << "% per trade\n";
312
313 cout << "\nOpportunities, no minimum margin:\n";
314 const size_t unconstrained = list_opportunities(market, 0.0, 5);
315 cout << "Opportunities found: " << unconstrained << "\n";
316
317 // Option A of the plan: the margin lives in the distance functor. 0.2 % per
318 // trade asks 0.6 % from a triangle, so the thinner one disappears.
319 cout << "\nOpportunities with a minimum margin of 0.2% per trade:\n";
320 const size_t with_margin = list_opportunities(market, 0.002, 5);
321 cout << "Opportunities found: " << with_margin << "\n";
322
323 cout << "\nMost profitable cycle by total gain, bounded by its length:\n";
324 show_bounded(market, 2); // a round trip can only lose the fees
325 show_bounded(market, 3);
326
327 // Karp ranks by the mean weight of the arcs of the cycle, not by the total.
328 const auto karp = karp_minimum_mean_cycle(market, Log_Rate_Distance{trading_fee, 0.0});
329 cout << "\nKarp minimum mean cycle (profit per trade, not total profit):\n";
330 const Opportunity mean_cycle = describe(karp.cycle_nodes, karp.cycle_arcs);
331 cout << " " << mean_cycle.route << " (mean log-weight " << fixed << setprecision(5)
332 << static_cast<double>(karp.minimum_mean) << " per trade)\n";
333
334 return 0;
335}
Minimum mean cycle in directed graphs (Karp algorithm).
Enumeration of negative cycles and bounded-length most negative cycle in directed graphs.
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
Generic key-value map implemented on top of a binary search tree.
Pair * insert(const Key &key, const Data &data)
Insert a key-value pair.
Data & find(const Key &key)
Find the value associated with key.
bool has(const Key &key) const noexcept(nothrow_search)
Return whether key is in the map.
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
Definition ah-dry.H:1475
DynList< Negative_Cycle_Item< GT, typename Distance::Distance_Type > > find_disjoint_negative_cycles(const GT &g, const size_t max_cycles, const Negative_Cycle_Exclusion exclusion=Negative_Cycle_Exclusion::Min_Weight_Arc, Distance distance=Distance(), SA sa=SA())
Find up to max_cycles negative cycles, excluding arcs of each cycle found before searching for the ne...
Bounded_Cycle_Result< GT, typename Distance::Distance_Type > most_negative_cycle_bounded(const GT &g, const size_t max_length, Distance distance=Distance(), SA sa=SA())
Most negative simple cycle of at most max_length arcs, ranked by total cost (not by mean cost as Karp...
Min_Mean_Cycle_Result< GT, typename Distance::Distance_Type > karp_minimum_mean_cycle(const GT &g, Distance distance=Distance(), SA sa=SA())
Compute minimum mean cycle by Karp's algorithm.
std::string quote(const std::string &s)
Definition ca-dot.H:92
Main namespace for Aleph-w library functions.
T & swap(T &t1, T &t2)
Generic swap using object's swap method.
Definition ahTypes.H:123
and
Check uniqueness with explicit hash + equality functors.
STL namespace.
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Gsl_Compatible_Rng r
Dynamic array container with automatic resizing.
Dynamic key-value map based on balanced binary search trees.
Generic graph and digraph implementations.