The resource loading... loading...

FMZ Funding Rate Acquisition and Monitoring Strategy

Author: FMZ~Lydia, Created: 2024-11-04 14:54:42, Updated:

Multi-platform futures funding rate acquisition and monitoring strategy

Description:

This strategy is used to obtain and monitor funding rates from multiple futures platforms such as OKCoin, Binance, Bitget, etc. It polls the perpetual contract markets of various exchanges through parallel threads, and obtains funding rate data, while using a delay mechanism to optimize the request frequency.

This article makes some changes to the strategy to support display and funding rate alarm push functions.

Open source address: https://www.fmz.com/strategy/470345

Function:

  • Multi-platform support : Synchronize funding rates across multiple trading platforms and set different request delays for each platform.
  • Specific symbol acquisition : Supports obtaining the funding rate of specific trading pairs (such as BTC/USDT, ETH/USDT).
  • Optimize for different platforms : Distinguish between platforms that do not need to query each market one by one (such as Binance) and platforms that need to traverse all markets (such as OKCoin).
  • Rate display : Displays the funding rates of multiple trading platforms. Because the collection intervals are different, they are uniformly adjusted to 24h rates for direct comparison.
  • Rate warning push : A certain threshold can be set, and when the 24h equivalent rate exceeds the customization, it will be pushed to the FMZ mobile APP.

Directions:

You can adjust the platform list, symbol list and polling interval as needed to meet your specific trading needs.

Strategy code

The script is divided into several main parts:

  1. startFundingWorker : Starts a separate thread for each exchange to monitor the funding rate to avoid throttling caused by a single thread requesting too much data.
  2. getFundings : Reads funding rate data for a specified exchange from storage.
  3. UpdateStatus : Processes and updates the funding rate table for all exchanges, displays the aggregated data as a table, and logs the symbols with high fees.
  4. main : Starts the main program, starts the monitoring thread and regularly updates the aggregated funding rate status.
// Start the funding rate monitoring thread and create a separate thread for each exchange's funding rate data
function startFundingWorker() {
    exchanges.forEach((_, pos) => {
        __Thread(function (pos) {
            let e = exchanges[pos]
            let eName = e.GetName()
            // Set request delays for different exchanges to prevent frequent requests from causing throttling
            let delaySettings = {
                'Futures_OKCoin': 20,
                'Futures_Binance': 500,
                'Futures_MEXC': 100,
            }
            // Need to traverse the list of exchange names for all markets, these exchanges do not support getting all trading pairs at once
            let needInterate = ['Futures_OKCoin', 'Futures_Bitget','Futures_OKX', 'Futures_KuCoin', 'Futures_MEXC'] 
            // Set delay based on exchange name
            let delay = function () {
                let n = delaySettings[eName]
                if (n) {
                    Sleep(n)
                }
            }
            // Set the update interval to update every two minutes
            let epoch = 60000 * 2;
            let ts = 0;
            let fundings = {}
            // Infinite loop, get funding rate at fixed intervals
            while (true) {
                let now = new Date().getTime()
                if (now - ts < epoch) {
                    // If the update cycle is not reached, pause for 1 second and then continue checking
                    Sleep(1000)
                    continue
                }
                let markets = e.GetMarkets()
                if (!markets) {
                    // If market information cannot be obtained, try again after a delay
                    Sleep(1000)
                    continue
                }
                // If the exchange is in the list that needs to be traversed, request the funding rate for each market
                if (needInterate.includes(eName)) {
                    for (let symbol in markets) {
                        if (symbol.includes('.swap') && symbol.includes('_USDT')) {
                            let ret = e.GetFundings(symbol)
                            if (ret) {
                                for (let r of ret) {
                                    fundings[r.Symbol] = r
                                }
                            }
                            delay();
                        }
                    }
                } else {
                    // For exchanges not in the traversal list, only request the funding rate of USDT.swap
                    let ret = e.GetFundings('USDT.swap')
                    if (ret) {
                        for (let r of ret) {
                            fundings[r.Symbol] = r
                        }
                    }
                }
                // Update data timestamp
                ts = now
                // Stores the exchange's funding rate data
                __threadSetData(0, eName+"_funding", fundings)
            }
        }, pos)
    })
}

// Get the funding rate data of the specified exchange
function getFundings(eName) {
    let efundings = __threadGetData(0, eName+"_funding")
    if (!efundings) {
        return null
    }
    return efundings
}

// Update the funding rate table and display it in the log
function UpdateStatus(){
    let table = { 
        type: 'table', 
        title: 'Funding Rate%', 
        cols: ['index', 'symbol'], // Initialization column, containing symbol
        rows: [] 
    };
    let fundingRates = {};
    exchanges.forEach((e) => {
        let eName = e.GetName();
        if (fundings[eName]) {
            for (let symbol in fundings[eName]) {
                // Parse short symbol names and remove unnecessary prefixes
                let short_symbol = symbol.split('_')[0].replace(/^(100|1000|10000|100000|1000000|10000000)|^(100|1000|10000|100000|1000000|10000000)$/g, '');
                let rate = fundings[eName][symbol].Rate;
                let day = 24 / (fundings[eName][symbol].Interval / 3600000)
                // Initialize symbol data structure
                if (!fundingRates[short_symbol]) {
                    fundingRates[short_symbol] = { total: 0, count: 0,  day_rate: {},  next_time: {}, last_time:0};
                }
                // Record and push rates that exceed the threshold
                if (Math.abs(rate) > 0.01 && Date.now() - fundingRates[short_symbol].last_time > 30*60*1000) {
                    Log(e.GetName(), symbol, rate, '@')
                    fundingRates[short_symbol].last_time = Date.now()
                }
                fundingRates[short_symbol].total += rate;
                fundingRates[short_symbol].count++;
                fundingRates[short_symbol].day_rate[eName] = _N(rate * day , 6); // Record rates
                fundingRates[short_symbol].next_time[eName] = _N((fundings[eName][symbol].Time - Date.now()) / 3600000 , 1) + 'h'
            }
        }
    });
    // Added rate columns and next update time columns for each exchange
    for (let e of exchanges) {
        table.cols.push(e.GetName()+' Rate');
        table.cols.push('Next Time');
    }
   
    table.cols.push('Average Rate'); // Add an average rate column
    let i = 0;
    // Iterate over each symbol and fill in the data
    for (let symbol in fundingRates) {
        let data = fundingRates[symbol];
        if (data.count == 1) {
            continue // Symbols containing only a single data point are ignored
        }
        let averageRate = data.total / data.count; // Calculate average rate
        let row = [i++, symbol];
        for (let e of exchanges) {
            row.push(data.day_rate[e.GetName()] || null); // Filling the fees of various exchanges
            row.push(data.next_time[e.GetName()] || null);
        }
        row.push(_N(averageRate, 6)); // Filling average rate
        table.rows.push(row);
    }
    LogStatus('`' + JSON.stringify(table) + '`');
}

// Main function, start funding rate monitoring and status update
var fundings = {}
function main() {
    startFundingWorker() // Start monitoring threads for each exchange
    while (true) {
        exchanges.forEach((e) => {
            let eName = e.GetName()
            let eFundings = getFundings(eName)
            fundings[eName] = eFundings
        })
        Sleep(15000) // Update every 15 seconds
        UpdateStatus()
    }
}

More