|
Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
|
Example: triangular arbitrage detection in a market of currency pairs. More...
#include <cmath>#include <iomanip>#include <iostream>#include <string>#include <utility>#include <Min_Mean_Cycle.H>#include <Negative_Cycles.H>#include <tpl_array.H>#include <tpl_dynMapTree.H>#include <tpl_graph.H>Go to the source code of this file.
Functions | |
| int | main () |
Example: triangular arbitrage detection in a market of currency pairs.
A market is a digraph whose nodes are assets and whose arcs are trades. An arc a -> b carries the rate at which one unit of a turns into units of b. Trading around a cycle multiplies the rates, so the cycle is an arbitrage opportunity exactly when the product of its rates, after fees, exceeds one. Taking logarithms turns the product into a sum:
weight(a -> b) = -log(rate * (1 - fee))
and an opportunity is a cycle of negative total weight.
The example shows how to use the negative-cycle tools of Aleph-w on it:
find_disjoint_negative_cycles() lists several opportunities at once, not just the first one Bellman_Ford finds, and with Negative_Cycle_Exclusion::All_Arcs no two of them share a trade. That only diversifies the candidates: two cycles that share no trade can still need the same balance, so whether they can be executed together depends on capital, quantities and liquidity, which the caller has to check.most_negative_cycle_bounded() finds the most profitable cycle of at most a given number of trades. It ranks by total profit, unlike karp_minimum_mean_cycle(), which ranks by profit per trade and is shown for comparison.Log_Rate_Distance). The library applies no threshold of its own: the margin that covers latency and slippage is a business decision, and the functor is where it belongs.The searches take a const graph and keep their state in private arrays, so several threads may search the same graph as long as nobody modifies it. A price feed does modify it, so the search needs a consistent version of the market: either copy the graph while holding the same lock the feed takes to write it (copying alone does not synchronize anything), or have the feed publish immutable versions. A result refers to the graph that was searched, and its pointers are valid only while that graph is. To act on a result, identify each trade by something stable stored in the arc (an instrument id, venue and side) rather than by pointer: GraphCopyWithMapping (tpl_graph.H) only maps original nodes to copied ones (get_copy(original)), not back, and does not map arcs, which parallel trades between the same assets need. This example does not implement a feed.
Build and run:
cmake -S . -B build -DBUILD_EXAMPLES=ON cmake –build build –target crypto_arbitrage_example ./build/Examples/crypto_arbitrage_example
Definition in file crypto_arbitrage_example.cc.
| int main | ( | void | ) |
Definition at line 303 of file crypto_arbitrage_example.cc.
References Aleph::karp_minimum_mean_cycle().