7
focar em
350
Seguidores

Compartilhando a lógica da estratégia de arbitragem de diferença de preço à vista em várias bolsas

Criado em: 2022-06-27 21:26:27, atualizado em: 2024-12-02 21:35:44
comments   4
hits   9491

Compartilhando a lógica da estratégia de arbitragem de diferença de preço à vista em várias bolsas

Princípio da estratégia

Devido a razões de liquidez, quando há uma grande quantidade de venda ou retirada no mercado, inevitavelmente haverá grandes flutuações de preço, e haverá uma diferença momentânea de preço entre as bolsas. A estratégia é capturar esses momentos e executar transações rápidas para conclua o processo de comprar barato e vender caro. . Alguns clientes me perguntaram por que tenho tantas exchanges. Isso é inevitável. O que ganhamos dinheiro é a diferença instantânea de preço entre as exchanges. Quanto mais exchanges houver, mais oportunidades de diferença de preço haverá após o crossover.

Lógica central da estratégia
  1. Obtenha simultaneamente as informações de mercado de várias bolsas. É necessário obtê-las simultaneamente para reduzir o atraso na obtenção das informações de mercado. Para aquisição simultânea, você pode consultar o plug-in de ferramenta que compartilhei.Plugin simultâneo de múltiplas trocas
  2. Combine o preço de venda e o preço de compra de todas as bolsas para obter informações de cotação combinadas, onde RealPrice é o preço após a dedução da taxa de manuseio.
function createOrders(depths, askOrders, bidOrders) {
    let asksIndex = 0;
    let bidIndex = 0;
    for (let i = 0; i < depths.length; i++) {
        let exchangeTariff = getExchangeTariff(i);
        let asks = depths[i].Asks;
        let bids = depths[i].Bids;
        for (let j = 0; j < Math.min(asks.length, bids.length, 20); j++) {
            if (asks[j].Amount >= minTakerAmount) {
                askOrders[asksIndex] = {
                    "Price": asks[j].Price,
                    "Amount": asks[j].Amount,
                    "Fee": asks[j].Price * exchangeTariff,
                    "RealPrice": asks[j].Price * (1 + exchangeTariff),
                    "Index": i,
                };
                asksIndex++;
            }
            if (bids[j].Amount >= minTakerAmount) {
                bidOrders[bidIndex] = {
                    "Price": bids[j].Price,
                    "Amount": bids[j].Amount,
                    "Fee": bids[j].Price * exchangeTariff,
                    "RealPrice": bids[j].Price * (1 - exchangeTariff),
                    "Index": i,
                };
                bidIndex++;
            }
        }
    }
    askOrders.sort(function (a, b) {
        return a.RealPrice - b.RealPrice;
    });
    bidOrders.sort(function (a, b) {
        return b.RealPrice - a.RealPrice;
    });
}
  1. Calcule o spread de arbitragem mais lucrativo a partir das informações de mercado combinadas. Como estamos recebendo ordens, ou seja, comprando pelo menor preço de venda e vendendo pelo maior preço de oferta, desde que bid.RealPrice > ask.RealPrice, há espaço para lucro
function getArbitrageOrders(askOrders, bidOrders) {
    let ret = [];
    for (let i = 0; i < askOrders.length; i++) {
        for (let j = 0; j < bidOrders.length; j++) {
            let bidOrder = bidOrders[j];
            let askOrder = askOrders[i];
            if (bidOrder.Index === askOrder.Index) {
                continue
            }
            let minMigrateDiffPrice = ((askOrder.Price + bidOrder.Price) / 2 * minMigrateDiffPricePercent / 100);
            if (bidOrder.RealPrice - askOrder.RealPrice > minMigrateDiffPrice) {
                ret.push({
                    "Ask": askOrder,
                    "Bid": bidOrder,
                })
            }
        }
    }
    if (ret.length === 0) {
        ret.push({
            "Ask": askOrders[0],
            "Bid": bidOrders[0],
        });
    }
    //按最优价差排序
    ret.sort((a, b) => {
        return (b.Bid.RealPrice - b.Ask.RealPrice) - (a.Bid.RealPrice - a.Ask.RealPrice);
    });
    return ret;
}
  1. Agora que obtivemos as informações de spread de arbitragem no mercado, como decidimos se executamos a transação e quanto negociar? Aqui estão alguns pontos-chave a serem considerados:
  • Ativos remanescentes atuais
  • O tamanho do spread (se o spread for muito pequeno, ele apenas equilibrará a quantidade de moeda e, se o spread for grande o suficiente, ele maximizará o número de transações)
  • Número de pedidos pendentes
    var askOrder = arbitrageOrder.Ask;
    var bidOrder = arbitrageOrder.Bid;
    var perAmountFee = arbitrageOrder.Ask.Fee + arbitrageOrder.Bid.Fee;
    var minRealDiffPrice = (askOrder.Price + bidOrder.Price) / 2 * minDiffPricePercent / 100;
    var minMigrateDiffPrice = ((askOrder.Price + bidOrder.Price) / 2 * minMigrateDiffPricePercent / 100);
    var curRealDiffPrice = arbitrageOrder.Bid.RealPrice - arbitrageOrder.Ask.RealPrice;
    var buyExchange = exchanges[arbitrageOrder.Ask.Index];
    var sellExchange = exchanges[arbitrageOrder.Bid.Index];
    var buySellAmount = 0;
    if (curRealDiffPrice > minRealDiffPrice) {
        buySellAmount = math.min(
            bidOrder.Amount,
            askOrder.Amount,
            maxTakerAmount,
            runningInfo.Accounts[bidOrder.Index].CurStocks,
            runningInfo.Accounts[askOrder.Index].CurBalance / askOrder.Price
        );
    } else if (bidOrder.Index !== askOrder.Index) {
        if (migrateCoinEx == -1) {
            if (curRealDiffPrice > minMigrateDiffPrice && runningInfo.Accounts[bidOrder.Index].CurStocks - runningInfo.Accounts[askOrder.Index].CurStocks > maxAmountDeviation) {
                buySellAmount = math.min(
                    bidOrder.Amount,
                    askOrder.Amount,
                    maxTakerAmount,
                    runningInfo.Accounts[bidOrder.Index].CurStocks,
                    runningInfo.Accounts[askOrder.Index].CurBalance / askOrder.Price,
                    runningInfo.Accounts[bidOrder.Index].CurStocks - ((runningInfo.Accounts[bidOrder.Index].CurStocks + runningInfo.Accounts[askOrder.Index].CurStocks) / 2)
                );
                if (buySellAmount >= minTakerAmount) {
                    Log("启动交易所平衡!");
                }
            }
        } else if (migrateCoinEx == askOrder.Index) {
            if (curRealDiffPrice > minMigrateDiffPrice && runningInfo.Accounts[bidOrder.Index].CurStocks > 0) {
                buySellAmount = math.min(
                    bidOrder.Amount,
                    askOrder.Amount,
                    maxTakerAmount,
                    runningInfo.Accounts[bidOrder.Index].CurStocks,
                    runningInfo.Accounts[askOrder.Index].CurBalance / askOrder.Price
                );
                if (buySellAmount >= minTakerAmount) {
                    Log("启动货币迁移:", exchanges[bidOrder.Index].GetName(), "-->", exchanges[askOrder.Index].GetName());
                }
            }
        }
    }
  1. Uma vez que a quantidade do pedido é calculada, a transação pode ser executada. A estratégia usa o método de adicionar slippage diretamente para receber pedidos e fazer pedidos ao mesmo tempo
            var buyWait = buyExchange.Go("Buy", _N(askOrder.Price * (1.01), pricePrecision), buySellAmount);
            var sellWait = sellExchange.Go("Sell", _N(bidOrder.Price * (0.99), pricePrecision), buySellAmount);
            var startWaitTime = new Date().getTime()
            Sleep(3000);
            var buyOrder = buyWait.wait()
            var sellOrder = sellWait.wait()
  1. O que resta é a lógica de calcular lucros, lidar com stop losses para ordens falhadas, etc.
Os benefícios reais desta estratégia

Compartilhando a lógica da estratégia de arbitragem de diferença de preço à vista em várias bolsas Compartilhando a lógica da estratégia de arbitragem de diferença de preço à vista em várias bolsas Compartilhando a lógica da estratégia de arbitragem de diferença de preço à vista em várias bolsas

Exibição atual em tempo real, lógica central permanece inalterada, otimizada para suportar múltiplas moedas

https://www.fmz.com/robot/464965

Por fim, bem-vindo para se juntar à Laoqiu Quantitative Exchange: https://t.me/laoqiu_arbitrage