DEV Community

Time Flies
Time Flies

Posted on

Improve Your Trading Bot’s Win Rate with Funding Rate + Liquidation Data: A Practical CoinGlass API Integration Guide

In the crypto market, many trading bots focus only on price, volume, moving averages, RSI, MACD, and other traditional indicators. But if your bot trades BTC, ETH, or major altcoin perpetual contracts, watching spot price alone is far from enough.

The reason is simple: a large part of crypto market volatility comes from leverage in the derivatives market.

When longs become overcrowded, even a small price pullback can trigger large-scale long liquidations. When shorts are overcrowded, an upside breakout can trigger a short squeeze. For a trading bot, the real question is not only “how much has price moved,” but also:

  • Is the market overly long?
  • Are shorts being squeezed?
  • Is leveraged capital piling into one side?
  • Is one side at risk of forced liquidation?
  • Is the current signal a real trend continuation or a trap?

This is why Funding Rate and Liquidation Data are extremely valuable for trading bots.

With the CoinGlass API, developers can access derivatives market data such as funding rates, liquidation history, liquidation heatmaps, open interest, long/short ratios, order books, and more. CoinGlass API data can be used for quantitative trading, market research, risk management, and automated trading systems.

This article will cover:

  1. Why trading bots need funding rate and liquidation data
  2. How funding rates help identify market sentiment
  3. How liquidation data helps detect short-term risk and reversal opportunities
  4. How to integrate CoinGlass API data
  5. How to convert derivatives data into trading bot signals
  6. Python code examples and a practical strategy framework

Note: “Improving win rate” does not mean guaranteed profit. Funding rate and liquidation data help trading bots reduce blind entries, identify crowded trades, and improve risk control. They should be used as part of a complete trading system, not as standalone trading signals.


1. Why Trading Bots Should Not Only Look at Price

Many basic trading bots rely on price-driven logic, such as:

Bot Type Common Signal Main Problem
Trend-following bot Moving average crossover, breakout May chase into overheated leverage zones
Mean-reversion bot RSI overbought/oversold Can get crushed in strong trends
Grid bot Buy low, sell high within a range Vulnerable to one-sided market moves
High-frequency bot Short-term order book movement May ignore broader leverage risk
Arbitrage bot Price spread, funding spread Requires more complete market data

Price is only the result. Behind price movement, there are often deeper forces:

  • Derivatives leverage
  • Long and short positioning costs
  • Forced liquidation
  • Funding rate changes
  • Order book liquidity
  • Open interest changes
  • Large trader behavior

If a trading bot only reads candlesticks, it sees what has already happened. If it also connects to derivatives data, it can better understand the pressure behind price movement.

For example:

When BTC keeps rising and breaks above a previous high, a simple trend bot may continue to go long. But if funding rates are already extremely high, the upside liquidity has been swept, and liquidation data shows a large cluster of long liquidation risk below, chasing longs may become dangerous.

On the other hand, if BTC drops sharply, long liquidations spike, but price fails to break lower and funding rates return from extreme positive levels back to neutral, it may suggest that leverage has been flushed out and the market is entering a new balance.

This kind of judgment is difficult to make from price alone.


2. What Is Funding Rate and Why Is It Useful for Trading Bots?

Funding rate is the periodic payment exchanged between long and short positions in perpetual futures markets.

In simple terms:

Funding Rate Condition Market Meaning Possible Interpretation
Positive funding rate Longs pay shorts Market is leaning bullish; longs may be crowded
Negative funding rate Shorts pay longs Market is leaning bearish; shorts may be crowded
Extremely high funding rate Long positions become expensive Potential long overcrowding risk
Extremely low or negative funding rate Short positions become expensive Potential short squeeze risk
Funding rate returns to neutral Leverage sentiment cools down Market may be rebalancing

Funding rate is not a simple long or short signal. It is better understood as a market crowding indicator.

A trading bot can use funding rate to evaluate:

  • Whether the market is overly bullish
  • Whether the market is overly bearish
  • Whether a trend is still healthy
  • Whether there is a risk of a squeeze
  • Whether position size should be reduced
  • Whether certain high-risk trade signals should be filtered out

For example:

High funding rate does not mean “short immediately.”
It means “longs are crowded, so chasing longs may carry higher risk.”
Enter fullscreen mode Exit fullscreen mode

A strong trend can keep funding rates high for a long time. Therefore, funding rate should be combined with price action, liquidation data, open interest, and volatility.


3. What Is Liquidation Data and Why Is It More Important Than Normal Volume?

Liquidation data refers to forced position closures in derivatives markets when traders do not have enough margin to maintain their positions.

It is different from normal trading volume.

Normal volume tells you that trades happened.
Liquidation data tells you which side was forced out of the market.

It helps answer questions like:

  • Were longs liquidated?
  • Were shorts liquidated?
  • Is the market experiencing forced selling or forced buying?
  • Has one side of leverage been flushed out?
  • Is the price move driven by real demand or forced liquidation?
  • Are there concentrated liquidation zones nearby?

Examples:

Market Behavior Liquidation Data Interpretation
Price drops sharply + long liquidations spike Long leverage is being flushed
Price rises sharply + short liquidations spike Shorts are being squeezed
Price ranges sideways + liquidation decreases Leverage pressure is cooling
Small price move + unusually large liquidations Market leverage may be too high
Price quickly recovers after liquidation Possible stop-hunt or false breakout

Liquidation data is especially useful for risk filters.

For example:

  • If long liquidations spike within 15 minutes, the bot may avoid chasing shorts at the bottom.
  • If short liquidations continue rising while price breaks resistance, the bot may detect a possible short squeeze.
  • If funding rates are extremely high while long liquidations start increasing, the bot may reduce long exposure or tighten stop-loss rules.

4. How to Combine Funding Rate and Liquidation Data into Trading Signals

Using funding rate alone can be misleading.

A high funding rate does not mean price will fall immediately.
A negative funding rate does not mean price will rise immediately.
In strong trends, funding rates can remain extreme for a long time.

Using liquidation data alone can also be lagging.

Liquidations usually happen after strong price movement. If a bot reacts only after liquidation occurs, it may already be late.

A better approach is:

Use funding rate as the market sentiment background, and use liquidation data as a risk trigger.


5. Model 1: Long Crowding Risk

Condition Meaning
Funding rate stays positive and keeps rising Longs are becoming crowded
Price continues rising Bullish sentiment is strengthening
Open interest rises at the same time Leveraged capital is entering
Long liquidations start increasing Longs are beginning to get forced out
Price breaks short-term support Risk release may be triggered

Possible bot actions:

Scenario Action
Already holding long positions Reduce position or tighten stop-loss
Preparing to open a long Pause entry
Short strategy available Wait for confirmation before small short entry
Grid bot Reduce position size and widen grid spacing

6. Model 2: Short Squeeze Risk

Condition Meaning
Funding rate is negative Market is leaning short
Short liquidations start increasing Shorts are being forced out
Price breaks resistance Potential short squeeze
Volume increases Trend confirmation
Funding rate rises from negative toward neutral Bearish sentiment is being repaired

Possible bot actions:

Scenario Action
Trend-following bot Follow the breakout if confirmed
Arbitrage bot Monitor funding rate normalization
Existing short strategy Reduce leverage or exit
Risk management system Trigger short squeeze alert

7. Model 3: Reversal After Leverage Flush

Condition Meaning
One side experiences large liquidations Leverage has been flushed
Price does not continue breaking down/up Selling or buying pressure may be exhausted
Funding rate returns to neutral Market sentiment cools
Open interest declines Leverage is reduced
Price reclaims key level Reversal probability increases

Possible bot actions:

Scenario Action
Trend strategy Wait for direction confirmation
Mean-reversion strategy Test small reversal position
Risk system Reduce extreme market risk weight
High-frequency bot Monitor order book recovery

8. What Data Can CoinGlass API Provide?

For trading bots, the most useful derivatives data usually includes:

Data Type Value for Trading Bots Typical Use Case
Funding Rate Measures long/short cost and crowding Filter risky trend signals
Liquidation History Shows forced liquidation direction Detect leverage flushes
Open Interest Shows whether capital is entering Confirm trend strength
Long/Short Ratio Shows market positioning tendency Sentiment filter
Taker Buy/Sell Measures aggressive buying/selling Short-term confirmation
Order Book Shows liquidity distribution Execution and market making
Liquidation Heatmap Shows potential liquidation zones Support, resistance, risk control

For a basic trading bot upgrade, you can start with:

  1. Funding rate
  2. Liquidation history
  3. Open interest

For more advanced or institutional-level bots, you can add:

  1. Order book data
  2. Taker buy/sell data
  3. CVD
  4. Liquidation heatmap
  5. WebSocket real-time data

9. Basic CoinGlass API Integration

A typical CoinGlass API request uses the base URL:

https://open-api-v4.coinglass.com
Enter fullscreen mode Exit fullscreen mode

API requests generally require an API key in the request header:

CG-API-KEY
Enter fullscreen mode Exit fullscreen mode

Basic Python request structure:

import os
import requests

BASE_URL = "https://open-api-v4.coinglass.com"
API_KEY = os.getenv("COINGLASS_API_KEY")

headers = {
    "CG-API-KEY": API_KEY,
    "Accept": "application/json"
}

def get_data(endpoint, params=None):
    url = f"{BASE_URL}{endpoint}"
    response = requests.get(url, headers=headers, params=params, timeout=10)
    response.raise_for_status()
    return response.json()
Enter fullscreen mode Exit fullscreen mode

It is better not to hardcode your API key directly into the script. Use an environment variable instead:

export COINGLASS_API_KEY="your_api_key_here"
Enter fullscreen mode Exit fullscreen mode

10. Example 1: Fetch BTC Funding Rate History

The following example shows how to request BTC funding rate history.

Please note that specific endpoint names, parameters, and returned field names may change depending on API version, plan, and supported exchanges. Always confirm with the latest CoinGlass API documentation.

import os
import requests
import pandas as pd

BASE_URL = "https://open-api-v4.coinglass.com"
API_KEY = os.getenv("COINGLASS_API_KEY")

headers = {
    "CG-API-KEY": API_KEY,
    "Accept": "application/json"
}

def fetch_funding_rate(symbol="BTC", interval="1h", limit=100):
    endpoint = "/api/futures/fundingRate/oi-weight-ohlc-history"

    params = {
        "symbol": symbol,
        "interval": interval,
        "limit": limit
    }

    url = f"{BASE_URL}{endpoint}"
    response = requests.get(url, headers=headers, params=params, timeout=10)
    response.raise_for_status()

    return response.json()

data = fetch_funding_rate(symbol="BTC", interval="1h", limit=100)

print(data)
Enter fullscreen mode Exit fullscreen mode

If the response contains timestamp, open, high, low, and close values, you can convert it into a DataFrame:

def normalize_ohlc_response(raw):
    """
    Adjust field names based on the actual API response.
    This example assumes raw["data"] is a list of records containing
    time/open/high/low/close fields.
    """
    rows = raw.get("data", [])

    df = pd.DataFrame(rows)

    if "time" in df.columns:
        df["time"] = pd.to_datetime(df["time"], unit="ms")

    return df

funding_raw = fetch_funding_rate("BTC", "1h", 100)
funding_df = normalize_ohlc_response(funding_raw)

print(funding_df.head())
Enter fullscreen mode Exit fullscreen mode

11. Example 2: Fetch BTC Liquidation History

A liquidation history endpoint may look like this:

/api/futures/liquidation/aggregated-history
Enter fullscreen mode Exit fullscreen mode

Python example:

import os
import requests
import pandas as pd

BASE_URL = "https://open-api-v4.coinglass.com"
API_KEY = os.getenv("COINGLASS_API_KEY")

headers = {
    "CG-API-KEY": API_KEY,
    "Accept": "application/json"
}

def fetch_liquidation_history(
    symbol="BTC",
    exchanges="Binance,OKX,Bybit",
    interval="1h",
    limit=100
):
    endpoint = "/api/futures/liquidation/aggregated-history"

    params = {
        "exchange_list": exchanges,
        "symbol": symbol,
        "interval": interval,
        "limit": limit
    }

    url = f"{BASE_URL}{endpoint}"
    response = requests.get(url, headers=headers, params=params, timeout=10)
    response.raise_for_status()

    return response.json()

liquidation_raw = fetch_liquidation_history(
    symbol="BTC",
    exchanges="Binance,OKX,Bybit",
    interval="1h",
    limit=100
)

print(liquidation_raw)
Enter fullscreen mode Exit fullscreen mode

Convert the response into a DataFrame:

def normalize_liquidation_response(raw):
    """
    Adjust field names based on the actual API response.
    Common fields may include time, long_liquidation,
    short_liquidation, etc.
    """
    rows = raw.get("data", [])
    df = pd.DataFrame(rows)

    if "time" in df.columns:
        df["time"] = pd.to_datetime(df["time"], unit="ms")

    return df

liq_df = normalize_liquidation_response(liquidation_raw)

print(liq_df.head())
Enter fullscreen mode Exit fullscreen mode

12. Merge Funding Rate and Liquidation Data

Now we can merge funding rate data and liquidation data into one signal table.

def merge_market_data(funding_df, liq_df):
    """
    Merge funding rate data and liquidation data by timestamp.
    Field names need to be adjusted according to the actual API response.
    """

    funding = funding_df.copy()
    liquidation = liq_df.copy()

    funding = funding.sort_values("time")
    liquidation = liquidation.sort_values("time")

    merged = pd.merge_asof(
        funding,
        liquidation,
        on="time",
        direction="nearest",
        tolerance=pd.Timedelta("5min")
    )

    return merged

market_df = merge_market_data(funding_df, liq_df)

print(market_df.tail())
Enter fullscreen mode Exit fullscreen mode

Assume the merged data contains the following fields:

Field Meaning
time Timestamp
funding_close Funding rate close value
funding_high Highest funding rate in the period
funding_low Lowest funding rate in the period
long_liquidation Long liquidation amount
short_liquidation Short liquidation amount
total_liquidation Total liquidation amount

If the actual field names are different, rename them during preprocessing:

market_df = market_df.rename(columns={
    "close": "funding_close",
    "longLiquidation": "long_liquidation",
    "shortLiquidation": "short_liquidation"
})
Enter fullscreen mode Exit fullscreen mode

13. Build a Simple Trading Bot Signal Model

The following example is not a complete trading strategy. It is a risk filter.

Its goal is to help a trading bot classify the current derivatives market environment.

Signal Meaning
LONG_CROWDED Long side is crowded; avoid aggressive long entries
SHORT_CROWDED Short side is crowded; avoid aggressive short entries
LONG_LIQUIDATION_SPIKE Long liquidation spike
SHORT_LIQUIDATION_SPIKE Short liquidation spike
NEUTRAL Neutral market environment
RISK_OFF Abnormal liquidation environment; reduce trading activity
def calculate_zscore(series, window=24):
    rolling_mean = series.rolling(window).mean()
    rolling_std = series.rolling(window).std()
    return (series - rolling_mean) / rolling_std

def generate_derivatives_signal(df):
    data = df.copy()

    # Adjust fields according to the actual API response
    data["funding_z"] = calculate_zscore(data["funding_close"], window=24)
    data["long_liq_z"] = calculate_zscore(data["long_liquidation"], window=24)
    data["short_liq_z"] = calculate_zscore(data["short_liquidation"], window=24)

    signals = []

    for _, row in data.iterrows():
        funding_z = row.get("funding_z", 0)
        long_liq_z = row.get("long_liq_z", 0)
        short_liq_z = row.get("short_liq_z", 0)

        if funding_z > 2 and long_liq_z > 2:
            signal = "LONG_CROWDED_RISK"
        elif funding_z < -2 and short_liq_z > 2:
            signal = "SHORT_SQUEEZE_RISK"
        elif long_liq_z > 3 or short_liq_z > 3:
            signal = "RISK_OFF"
        elif funding_z > 1.5:
            signal = "LONG_CROWDED"
        elif funding_z < -1.5:
            signal = "SHORT_CROWDED"
        else:
            signal = "NEUTRAL"

        signals.append(signal)

    data["derivatives_signal"] = signals

    return data

signal_df = generate_derivatives_signal(market_df)

print(
    signal_df[
        ["time", "funding_close", "long_liquidation", "short_liquidation", "derivatives_signal"]
    ].tail()
)
Enter fullscreen mode Exit fullscreen mode

14. How to Connect This to a Trading Bot

Assume your bot originally uses a simple trend-following strategy:

def base_trend_signal(price_df):
    """
    Simple moving average strategy example.
    """
    df = price_df.copy()

    df["ma_fast"] = df["close"].rolling(20).mean()
    df["ma_slow"] = df["close"].rolling(60).mean()

    if df["ma_fast"].iloc[-1] > df["ma_slow"].iloc[-1]:
        return "BUY"
    elif df["ma_fast"].iloc[-1] < df["ma_slow"].iloc[-1]:
        return "SELL"
    else:
        return "HOLD"
Enter fullscreen mode Exit fullscreen mode

Now add the derivatives risk filter:

def final_trading_decision(price_signal, derivatives_signal):
    """
    Combine price signal and derivatives market signal.
    """

    # Avoid chasing longs when the long side is overcrowded
    if price_signal == "BUY" and derivatives_signal in [
        "LONG_CROWDED",
        "LONG_CROWDED_RISK",
        "RISK_OFF"
    ]:
        return "HOLD"

    # Avoid chasing shorts when the short side is overcrowded
    if price_signal == "SELL" and derivatives_signal in [
        "SHORT_CROWDED",
        "SHORT_SQUEEZE_RISK",
        "RISK_OFF"
    ]:
        return "HOLD"

    # In extreme risk environments, reduce trading frequency
    if derivatives_signal == "RISK_OFF":
        return "HOLD"

    return price_signal
Enter fullscreen mode Exit fullscreen mode

Full call example:

price_signal = "BUY"  # Example signal from your trend model
latest_derivatives_signal = signal_df["derivatives_signal"].iloc[-1]

decision = final_trading_decision(
    price_signal=price_signal,
    derivatives_signal=latest_derivatives_signal
)

print("Price Signal:", price_signal)
print("Derivatives Signal:", latest_derivatives_signal)
print("Final Decision:", decision)
Enter fullscreen mode Exit fullscreen mode

The goal is not to make the bot “predict the future.”
The goal is to help the bot understand when it should trade less.

Many strategies lose money not because the direction is always wrong, but because they keep executing signals mechanically in high-risk environments.

Original Signal Derivatives Environment Optimized Action
BUY Funding rate is extremely high Pause long entry
BUY Long liquidations just spiked Wait for confirmation
SELL Funding rate is deeply negative Pause short entry
SELL Short liquidations spike Avoid getting squeezed
BUY/SELL Total liquidation is abnormal Reduce position or pause trading

15. Add Position Management: Not Just Buy or Sell

Funding rate and liquidation data are especially useful for position sizing.

You can allow your trading bot to dynamically adjust position size according to derivatives market risk:

def calculate_position_size(base_size, derivatives_signal):
    """
    Adjust position size based on derivatives risk signal.
    base_size represents the default position size.
    For example, 1.0 means 100% standard size.
    """

    risk_multiplier = {
        "NEUTRAL": 1.0,
        "LONG_CROWDED": 0.7,
        "SHORT_CROWDED": 0.7,
        "LONG_CROWDED_RISK": 0.4,
        "SHORT_SQUEEZE_RISK": 0.4,
        "RISK_OFF": 0.0
    }

    multiplier = risk_multiplier.get(derivatives_signal, 0.5)

    return base_size * multiplier

base_position_size = 1.0
latest_signal = signal_df["derivatives_signal"].iloc[-1]

position_size = calculate_position_size(base_position_size, latest_signal)

print("Adjusted Position Size:", position_size)
Enter fullscreen mode Exit fullscreen mode

This makes your bot more adaptive. Instead of going full size whenever a signal appears, it adjusts exposure according to market structure.


16. Practical Strategy Framework: Funding Rate + Liquidation Data

A more complete trading bot can be structured like this:

Module Input Data Purpose
Trend Module Candlesticks, moving averages, breakouts Determine base direction
Sentiment Module Funding rate, long/short ratio Measure market crowding
Risk Module Liquidation data, open interest change Detect leverage risk
Execution Module Order book, spread, slippage Improve entry and exit execution
Position Module Risk signal, volatility Adjust position size dynamically
Review Module Historical data, backtesting results Optimize parameters

A more robust trading bot workflow may look like this:

1. Fetch price data
2. Generate base trend signal
3. Fetch funding rate data
4. Fetch liquidation data
5. Calculate market crowding
6. Detect liquidation risk
7. Filter high-risk trading signals
8. Adjust position size dynamically
9. Execute trades
10. Record results and improve through backtesting
Enter fullscreen mode Exit fullscreen mode

17. Best Use Cases for CoinGlass API

1. Trend-Following Trading Bots

Trend bots are vulnerable to chasing tops or bottoms.
Funding rate helps identify overheated trends, while liquidation data helps detect leverage cascades.

Useful applications:

  • Reduce long entry weight when funding rates are extremely high
  • Confirm upside momentum when short liquidations increase
  • Avoid blind bottom-fishing when long liquidations are still expanding
  • Look for reversal opportunities after leverage flushes

2. Grid Trading Bots

Grid bots are most vulnerable to strong one-sided markets.
Liquidation data can help detect extreme market conditions, while funding rate helps evaluate whether the market is becoming one-sided.

Useful applications:

  • Pause new grid orders when liquidations spike
  • Widen grid spacing when funding rate becomes extreme
  • Resume normal trading after leverage is flushed
  • Reduce one-sided exposure when the market is crowded

3. Arbitrage Bots

Funding rate itself is a key variable for arbitrage strategies.

Funding rate differences across exchanges can create potential opportunities.

Useful applications:

  • Monitor funding rates across multiple exchanges
  • Identify abnormal funding rate pairs
  • Combine open interest to judge whether the opportunity is sustainable
  • Combine liquidation data to detect event risk

4. Risk Management Bots

A risk management bot does not necessarily place trades.
It can provide market risk status to the strategy system.

Useful applications:

  • Liquidation spike alerts
  • Leverage crowding alerts
  • Long/short squeeze alerts
  • Automatic reduction of trading frequency
  • Pausing trading during extreme market conditions

18. Common Mistakes

Mistake 1: “High Funding Rate Means Short Immediately”

Not necessarily.

In strong trends, funding rates can stay high for a long time. If you short only because funding is high, you may end up fighting the trend.

A better logic is:

High funding rate = Longs are crowded
Longs are crowded ≠ Short immediately
Longs are crowded + Price weakness + Long liquidation spike = Stronger short condition
Enter fullscreen mode Exit fullscreen mode

Mistake 2: “Large Liquidation Means Open a Reversal Trade Immediately”

Not always.

Large liquidation can mark the end of a move, but it can also be part of a trend continuation. The key is how price behaves after liquidation.

Post-Liquidation Behavior Interpretation
Price continues breaking down/up Trend may continue
Price quickly reclaims the level Possible false breakout
Price consolidates Wait for new direction
Funding rate returns to neutral Leverage pressure may be cooling

Mistake 3: Only Looking at One Exchange

Crypto is a multi-exchange market.

If your bot only watches one exchange, it may miss leverage changes on other major venues.

One major advantage of CoinGlass API is that it helps developers monitor multi-exchange derivatives data in a more unified way.


19. What to Check Before Going Live

Before connecting funding rate and liquidation data to a live trading bot, check the following:

Checklist Description
Data latency Make sure the API speed matches your strategy frequency
Field stability Handle field changes according to documentation
Retry logic Automatically retry failed API requests
Rate limit control Avoid excessive request frequency
Caching Cache data when appropriate
Backtesting Do not go live without historical validation
Risk-first design Protect capital during extreme market events
Logging Record every signal and API response

Example: add retry logic to API requests.

import time
import requests

def safe_get(url, headers, params=None, retries=3, sleep_seconds=2):
    last_error = None

    for attempt in range(retries):
        try:
            response = requests.get(
                url,
                headers=headers,
                params=params,
                timeout=10
            )
            response.raise_for_status()
            return response.json()

        except requests.RequestException as error:
            last_error = error
            print(f"Request failed, attempt {attempt + 1}/{retries}: {error}")
            time.sleep(sleep_seconds)

    raise last_error
Enter fullscreen mode Exit fullscreen mode

20. Full Example: Derivatives Risk Filter

Below is a simplified full example that combines the logic discussed above.

import os
import requests
import pandas as pd

BASE_URL = "https://open-api-v4.coinglass.com"
API_KEY = os.getenv("COINGLASS_API_KEY")

headers = {
    "CG-API-KEY": API_KEY,
    "Accept": "application/json"
}

def request_api(endpoint, params=None):
    url = f"{BASE_URL}{endpoint}"

    response = requests.get(
        url,
        headers=headers,
        params=params,
        timeout=10
    )

    response.raise_for_status()
    return response.json()

def fetch_funding(symbol="BTC", interval="1h", limit=100):
    endpoint = "/api/futures/fundingRate/oi-weight-ohlc-history"

    params = {
        "symbol": symbol,
        "interval": interval,
        "limit": limit
    }

    return request_api(endpoint, params)

def fetch_liquidation(symbol="BTC", interval="1h", limit=100):
    endpoint = "/api/futures/liquidation/aggregated-history"

    params = {
        "exchange_list": "Binance,OKX,Bybit",
        "symbol": symbol,
        "interval": interval,
        "limit": limit
    }

    return request_api(endpoint, params)

def to_dataframe(raw):
    rows = raw.get("data", [])
    df = pd.DataFrame(rows)

    if "time" in df.columns:
        df["time"] = pd.to_datetime(df["time"], unit="ms")

    return df

def zscore(series, window=24):
    mean = series.rolling(window).mean()
    std = series.rolling(window).std()
    return (series - mean) / std

def build_signal_table(funding_df, liq_df):
    funding = funding_df.copy()
    liquidation = liq_df.copy()

    # Adjust these field names according to the actual API response
    funding = funding.rename(columns={
        "close": "funding_close"
    })

    liquidation = liquidation.rename(columns={
        "longLiquidation": "long_liquidation",
        "shortLiquidation": "short_liquidation"
    })

    funding = funding.sort_values("time")
    liquidation = liquidation.sort_values("time")

    df = pd.merge_asof(
        funding,
        liquidation,
        on="time",
        direction="nearest",
        tolerance=pd.Timedelta("5min")
    )

    df["funding_z"] = zscore(df["funding_close"], 24)
    df["long_liq_z"] = zscore(df["long_liquidation"], 24)
    df["short_liq_z"] = zscore(df["short_liquidation"], 24)

    signals = []

    for _, row in df.iterrows():
        funding_z = row.get("funding_z", 0)
        long_liq_z = row.get("long_liq_z", 0)
        short_liq_z = row.get("short_liq_z", 0)

        if funding_z > 2 and long_liq_z > 2:
            signal = "LONG_CROWDED_RISK"
        elif funding_z < -2 and short_liq_z > 2:
            signal = "SHORT_SQUEEZE_RISK"
        elif long_liq_z > 3 or short_liq_z > 3:
            signal = "RISK_OFF"
        elif funding_z > 1.5:
            signal = "LONG_CROWDED"
        elif funding_z < -1.5:
            signal = "SHORT_CROWDED"
        else:
            signal = "NEUTRAL"

        signals.append(signal)

    df["signal"] = signals

    return df

def position_multiplier(signal):
    table = {
        "NEUTRAL": 1.0,
        "LONG_CROWDED": 0.7,
        "SHORT_CROWDED": 0.7,
        "LONG_CROWDED_RISK": 0.4,
        "SHORT_SQUEEZE_RISK": 0.4,
        "RISK_OFF": 0.0
    }

    return table.get(signal, 0.5)

if __name__ == "__main__":
    funding_raw = fetch_funding("BTC", "1h", 100)
    liquidation_raw = fetch_liquidation("BTC", "1h", 100)

    funding_df = to_dataframe(funding_raw)
    liq_df = to_dataframe(liquidation_raw)

    signal_df = build_signal_table(funding_df, liq_df)

    latest = signal_df.iloc[-1]
    latest_signal = latest["signal"]
    multiplier = position_multiplier(latest_signal)

    print("Latest time:", latest["time"])
    print("Derivatives signal:", latest_signal)
    print("Position multiplier:", multiplier)
Enter fullscreen mode Exit fullscreen mode

21. Conclusion: A Trading Bot Needs Market Context, Not Just Price Signals

Many trading bots fail not because the code is bad, but because they do not understand the market environment.

A breakout is not always a real breakout.
A volume spike is not always the start of a trend.
A high funding rate does not always mean the market will fall.
A large liquidation event does not always mean the move is over.

But when these data points are combined, a trading bot can better understand the structure behind price movement.

Data Problem It Solves
Price Is the market going up or down?
Volume Is trading activity increasing?
Funding Rate Which side is more crowded?
Liquidation Data Which side is being forced out?
Open Interest Is new capital entering?
Long/Short Ratio How are traders positioned?
Order Book Where is liquidity located?
Heatmap Where are potential support/resistance and liquidation zones?

The value of CoinGlass API is that it helps trading bots move from “watching price” to “understanding derivatives market structure.”

For futures trading, quantitative strategies, arbitrage systems, grid bots, and risk management systems, this type of data is no longer just a nice-to-have feature. It is becoming part of the core trading infrastructure.

Funding rate and liquidation data cannot guarantee that every trade will be profitable. However, they can help your trading bot:

  • Avoid blindly chasing longs when the market is extremely crowded
  • Avoid blindly shorting when shorts are already overcrowded
  • Identify abnormal moves caused by forced liquidation
  • Reduce position size during extreme market conditions
  • Improve risk awareness
  • Make decisions based on market structure instead of price alone

If you are building a trading bot, or if you already have a K-line-based trading system, integrating CoinGlass API funding rate and liquidation data is one of the most practical upgrades you can make.

Top comments (0)