The resource loading... loading...

Introduction to the Lead-Lag suite in digital currency (3)

Author: The grass, Created: 2024-12-24 15:43:36, Updated: 2024-12-26 12:14:45

img

In the previous article, we introduced the leverage effect of cross-exchanges. This time, we will explore in depth how to apply the lead-lag effect to high-frequency trading, where high-frequency trading requires capturing tiny price differences in a very short time and making a quick profit. The lead-lag effect provides traders with predictive information to help them judge short-term price movements and thus leverage between different exchanges.

The following is correct:Simplified open sourceThe code for this original strategy is simple, once very profitable, and is currently not available, for reference only.


Lead-Lag high frequency strategy

The so-called lead-lag trend can be understood as the price of some exchanges (or certain indicators) will lead more sharply in the overall market changes (lead), while other exchanges or other indicators will be relatively laggy. In this strategy, the lead price, price, price, or price lags represent the behavior of different exchanges, respectively. They are mainstream exchanges that are more sensitive to market news or whose trading depth is different from that of the participants, which will cause the price of these exchanges to fluctuate one step earlier when there is a large buy or sell order.

Order books from multiple exchanges seized

The strategy takes order book data from different exchanges almost simultaneously, such as buy, sell, hang, etc.; then compares the mid-pricing (i.e. the average of buy and sell) of different exchanges to infer market dynamics.

Trend signals are judged

The strategy focuses on price movements on three external exchanges (okex, binance, huobipro):

Here, each trend X is determined by the difference between the current price rise and the past price rise above a certain threshold. After adding up the up/down signals from the three exchanges, if the overall trend is > 0, the strategy buys; if the trend is < 0, the strategy sells.

One-way down and wind control

The strategy only buys or sells once the trend is confirmed, and cancels previous orders before each order is placed (i.e. avoids unexpected bookings that lead to risk accumulation). At the same time, the script also sets up modules such as leverage, bulk operation, wind control monitoring, etc. to show that in real time, multiple accounts and multi-currency pairs are used simultaneously, thus expanding the strategy's leveraged trading frequency and leveraged capital utilization efficiency.

The strategy is also a high-frequency strategy, which does not focus on the profit or loss of each order, and does not require a stop loss, so long as the probability is profitable.


The FMZ strategy is implemented

Parameter setting

// 超参设置
const SYMBOL = "BTC_USDT"; // 交易对
const PRICE_INCREMENT = 0.1; // 价格增量
const LEVEL = 10; // 趋势判断的灵敏度
const RATIO = 10; // 下单价格调整比例
const INTERVAL = 200; // 时间间隔(毫秒)
const S_AMOUNT = 0.02; // 默认交易量
const MIN_AMOUNT = 0.005; // 最小交易量

// 初始状态
let buyOrders = [];
let sellOrders = [];
let previousPrices = [0, 0, 0]; // 存储之前的价格
let loop = 0;

Core logic: data acquisition and judgement trends

// 获取订单簿数据
function fetchOrderBooks() {
    let orderBooks = [];
    let tasks = [];

    // 启动所有交易所的异步获取订单簿任务
    for (let i = 0; i < exchanges.length; i++) {
        // 假设每个交易所对象都可以调用Go方法
        let task = exchanges[i].Go("GetDepth");
        tasks.push({ index: i, task: task });
    }

    // 等待所有任务完成并收集结果
    for (let i = 0; i < tasks.length; i++) {
        let { index, task } = tasks[i];
        try {
            // 等待异步任务返回结果
            let depth = task.wait(1000);

            // 检查返回的数据是否有效
            if (!depth || !depth.Bids || !depth.Asks) {
                throw new Error("返回的订单簿数据无效");
            }

            // 将有效的订单簿数据添加到结果数组
            orderBooks[index] = depth;
        } catch (error) {
            // 记录错误日志
            Log(`获取交易所${index}订单簿失败: ${error.message}`);

            // 添加默认的订单簿数据以避免崩溃
            orderBooks[index] = {
                Bids: [[0, 0]],
                Asks: [[0, 0]]
            };
        }
    }

    return orderBooks;
}


// 判断趋势
function calculateTrend(orderBooks) {
    let trends = [];
    for (let i = 0; i < orderBooks.length; i++) {
        const midPrice = (orderBooks[i].Bids[0][0] + orderBooks[i].Asks[0][0]) / 2;
        if (midPrice > previousPrices[i] + LEVEL * PRICE_INCREMENT) {
            trends.push(1); // 上升趋势
        } else if (midPrice < previousPrices[i] - LEVEL * PRICE_INCREMENT) {
            trends.push(-1); // 下降趋势
        } else {
            trends.push(0); // 无显著趋势
        }
        previousPrices[i] = midPrice; // 更新价格记录
    }
    return trends.reduce((a, b) => a + b, 0); // 返回总体趋势
}

Orders placed and cancelled

// 取消所有挂单
function cancelOrders(orders) {
    for (let orderId of orders) {
        try {
            exchanges[0].CancelOrder(orderId); // 默认使用主交易所
            Log(`取消订单: ${orderId}`);
        } catch (error) {
            Log(`取消订单失败: ${error.message}`);
        }
    }
}

// 创建买单
function createBuyOrder(price, amount) {
    try {
        const orderId = exchanges[0].Buy(price, amount);
        buyOrders.push(orderId);
        Log(`创建买单: 价格 ${price}, 数量 ${amount}`);
    } catch (error) {
        Log(`创建买单失败: ${error.message}`);
    }
}

// 创建卖单
function createSellOrder(price, amount) {
    try {
        const orderId = exchanges[0].Sell(price, amount);
        sellOrders.push(orderId);
        Log(`创建卖单: 价格 ${price}, 数量 ${amount}`);
    } catch (error) {
        Log(`创建卖单失败: ${error.message}`);
    }
}

The strategic logic

function main() {
    while (true) {
        try {
            // 获取订单簿数据
            const orderBooks = fetchOrderBooks();

            // 计算趋势
            const trend = calculateTrend(orderBooks);
            Log(`当前趋势: ${trend}`);

            // 取消挂单
            cancelOrders(buyOrders);
            cancelOrders(sellOrders);
            buyOrders = [];
            sellOrders = [];

            // 根据趋势下单
            if (trend > 0 && loop > 0) {
                const price = _N(orderBooks[0].Bids[0][0] + RATIO * PRICE_INCREMENT, 2);
                const amount = _N(Math.max(S_AMOUNT, MIN_AMOUNT), 4);
                createBuyOrder(price, amount);
            } else if (trend < 0 && loop > 0) {
                const price = _N(orderBooks[0].Asks[0][0] - RATIO * PRICE_INCREMENT, 2);
                const amount = _N(Math.max(S_AMOUNT, MIN_AMOUNT), 4);
                createSellOrder(price, amount);
            }

            // 循环计数与间隔
            loop++;
            Sleep(INTERVAL);

        } catch (error) {
            Log(`主逻辑错误: ${error.message}`);
        }
    }
}

Analysis of the reasons for the failure of strategy

The market becomes efficient

When more and more quantitative or high-frequency strategies are involved and the same lead-lag relationship is found, large amounts of money can quickly smooth out this price differential. The market becomes increasingly asynchronous, and it is difficult for strategies to profit from small price differences without risk hedging or short-term hedging.

Exchange restrictions or changes in fees

As the fee structure of different exchanges changes, the profitability of high-frequency trading strategies is greatly discounted once the cost of the procedure exceeds the profit of the swap; or exchanges accelerate the shooting speed, limit the frequency, reduce the delay, and also make the strategies that rely on inconsistent delays ineffective.

Decline in liquidity and slippage

When the market is under-traded, the high-frequency strategy often experiences a more serious slide; or the large order will quickly push the price, causing the expected high order to be affected by its own single instead, causing a decrease in earnings.

Changes in market volatility

Some strategies are particularly useful in high volatility scenarios or in specific cycles of volatility, where the strategy loses its environment and may even make frequent losses when the market is flat or volatile.


Summary

The key point of this high-frequency trading strategy lies in the capture of prices on multiple exchanges and the synthesis of hedging trends. It was once based on the Lead-Lag principle of ultra-high-frequency, fast-exit trading: observing which exchange's price moves first, and then triggering the prices of other exchanges to follow, from which to capture instantaneous spreads or short-term trends. However, as the author says, this strategy of relying on the market environment, strategy homogenization, processing fees and frequency limit changes, the strategy of moving hedging prices after the movement is gradually becoming less useful, or even losing profitability.


More