USD Arbitrage with Rust 🦀

How High-Frequency Strategies Identify Inefficiencies in the Currency Market (USD)

Introduction

In the world of finance — especially in the foreign exchange (FX) market — milliseconds matter. High-Frequency Trading (HFT) strategies thrive on detecting temporary price inefficiencies, like those between the spot and futures markets for the U.S. dollar.

This price gap, known as the FX spread, might last only a fraction of a second, but it’s often enough to generate a profit. In this post, we’ll break down the math behind it and simulate the logic in pure Rust — no external libraries.

📉 What Is Currency Arbitrage?

This 5-cent difference can be caused by interest rates, liquidity imbalances, latency, or asymmetric market reactions.

The role of an HFT system is to:

🔢 The Math of Arbitrage

spread = sell_price - buy_price
spread > transaction_cost ⇒ oportunidade lucrativa

Example:

With a contract of $100,000, that’s R$4,000 profit, potentially in milliseconds.

🦀 Simulating FX Arbitrage in Pure Rust

Here’s a simple HFT-style simulation in Rust using threads and channels.

use rand::Rng;


        use std::thread;
        use std::sync::mpsc;
        use std::time::{Duration, Instant};
        
        fn main() {
            let (tx, rx) = mpsc::channel();
        
            // Simulate spot dollar market (faster, more liquid)
            let tx1 = tx.clone();
            thread::spawn(move || {
                let mut spot = 5.00;
                loop {
                    spot += offset();
                    tx1.send(("spot", spot)).unwrap();
                    thread::sleep(Duration::from_millis(150));
                }
            });
        
            // Simulate futures dollar market (slightly delayed)
            let tx2 = tx.clone();
            thread::spawn(move || {
                let mut future = 5.03;
                loop {
                    future += offset();
                    tx2.send(("future", future)).unwrap();
                    thread::sleep(Duration::from_millis(300));
                }
            });
        
            let mut spot = 0.0;
            let mut future = 0.0;
            let cost = 0.005; // operational cost per dollar
            let mut timer = Instant::now();
        
            for (market, price) in rx {
                match market {
                    "spot" => spot = price,
                    "future" => future = price,
                    _ => {}
                }
        
                let spread = future - spot;
                if spread > cost {
                    println!(
                        "💰 Arbitrage detected: Buy spot at R${:.2} and sell future at R${:.2} | Gross profit: R${:.2}",
                        spot, future, spread - cost
                    );
                }
        
                if timer.elapsed().as_secs() >= 1 {
                    println!("🟢 Spot: R${:.2} | 🔵 Future: R${:.2}", spot, future);
                    timer = Instant::now();
                }
            }
        }
        
        // Simulated price fluctuation
        fn offset() -> f64 {
            let millis = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .subsec_millis();
            let osc = (millis % 5) as f64 - 2.0;
            osc * 0.001 // fluctuation between -0.002 and +0.002
        }
        
Logo

🧾 Code Breakdown

📌 Conclusion

Currency arbitrage is a fertile ground for high-frequency strategies, even in emerging markets like Brazil. While this is a simplified model, it mirrors real-world systems: spotting fleeting price differences and acting with mathematical precision.

In the next post, we’ll explore how HFT strategies impound information into prices — and as always, we’ll do it with Rust code you can learn from and build on.

Let’s go deeper, one tick at a time. 🦀📈