跳到正文
原文
Google AI:DEV 作者专属(RSS)· Polymarket Trader & Web3 Dev·· 3 小时前AI 评分30

如何构建 Polymarket TWAP 订单簿失衡交易机器人

Building a Polymarket TWAP Order Book Imbalance Bot

AI 导读

一种面向 Polymarket 的交易机器人研究框架,将订单簿失衡(OBI)与 TWAP 参考价结合,用 OBI×TWAP 偏离度×持续性作为信号,而非把失衡当作独立买卖信号。该框架基于 Polymarket 实时订单簿事件中的买卖档位、价格、数量与时间戳重建订单簿,并强调需规避前视偏差、快照偏差、选择偏差、幸存者偏差与过拟合。

正文

Explore how Polymarket TWAP signals and order book imbalance can be combined to detect short-term pressure, liquidity shifts, and execution risk.

The interesting signal is not imbalance. It is imbalance relative to TWAP.

An order book can look strongly bullish while price barely moves. A few seconds later, the same imbalance disappears as liquidity is cancelled or replenished.

That creates an important distinction for a Polymarket trading bot:

Is the order book showing genuine information, or merely temporary liquidity?

This is where TWAP becomes useful.

Rather than treating order book imbalance as an independent buy/sell signal, a more interesting approach is to ask whether current liquidity pressure agrees with the direction implied by a reference TWAP.

That turns a simple order-book statistic into a contextual market-microstructure signal.

About the Author

Soulcrancerdev specializes in the engineering and quantitative research behind automated prediction-market trading.

Get in touch:
Github: https://github.com/thesoulcrancerdev/poly-trading-strategies
X: https://x.com/soulcrancerdev
Community: https://t.me/+SxEC7bVXYyphNzI5
Telegram: https://t.me/soulcrancerdev
Gmail: mailto:misssilverbeauty0927@gmail.com
Youtube: https://youtube.com/@soulcrancerdev

The Core Question

Can Polymarket TWAP order book imbalance identify situations where visible liquidity pressure is aligned with an underlying price trend rather than being temporary noise?

The answer cannot be assumed from the indicator itself. It has to be tested.


What the Order Book Actually Gives You

Polymarket's current real-time market-data documentation exposes order-book events containing bid and ask levels, prices, sizes, timestamps, and related market information. Price-change events can also contain the affected price, size, side, and best bid/ask. ([docs.polymarket.com][1])

That makes it possible to reconstruct a continuously changing book rather than repeatedly polling a snapshot.

A basic imbalance measure is:

OBI = \frac{B-A}{B+A}

where:

  • (B) = bid-side depth
  • (A) = ask-side depth

An OBI near +1 indicates substantially more displayed bid liquidity. An OBI near -1 indicates substantially more ask liquidity.

But there is an immediate problem.

Displayed liquidity is not the same thing as executed pressure.

Orders can be cancelled, replenished, moved, or simply remain irrelevant because the market never reaches them.

This is why using the raw imbalance alone can produce misleading signals.


The TWAP Context

Suppose the current Polymarket price is above its relevant TWAP.

That does not automatically mean the market should continue upward.

But now imagine three observations occurring together:

  1. Price is above TWAP.
  2. Order-book imbalance is strongly positive.
  3. Bid-side depth remains persistent across multiple observations.

The signal is more interesting because the order book is no longer being interpreted in isolation.

A useful conceptual framework is:

TWAP State → Order-Book Imbalance → Persistence → Price Reaction → Execution

The key word is persistence.

A single imbalance observation is weak evidence.

Repeated imbalance that survives book updates is potentially more informative.


A Better Imbalance Model

Instead of measuring only the first bid and ask levels, an experiment can aggregate several price levels:

OBI_k =
\frac{\sum_{i=1}^{k} w_i B_i -
\sum_{i=1}^{k} w_i A_i}
{\sum_{i=1}^{k} w_i B_i +
\sum_{i=1}^{k} w_i A_i}

where (w_i) gives greater importance to levels closer to the best price.

This matters because one large order at the top of the book can dominate a naive imbalance calculation.

A multi-level measure asks a different question:

Is liquidity actually distributed toward one side of the market?

Research on traditional limit-order markets has found that order-flow imbalance can explain short-horizon price changes, with the relationship affected by available market depth. That literature is not evidence that the same relationship automatically exists on Polymarket; it provides a hypothesis worth testing. ([OUP Academic][2])


The Signal Most Traders Miss: Persistence

Consider this hypothetical example.

Hypothetical example

At time (t_0):

  • Price = 0.61
  • TWAP = 0.59
  • OBI = +0.42

Five seconds later:

  • Price = 0.612
  • TWAP = 0.5905
  • OBI = +0.39

Ten seconds later:

  • Price = 0.615
  • TWAP = 0.591
  • OBI = +0.44

The interesting feature is not the +0.44.

It is the combination of positive imbalance, positive price/TWAP separation, and persistence.

A bot could therefore record:

Signal =
OBI \times TWAPDistance \times Persistence

This is not a validated trading formula. It is a research framework.

The purpose is to test whether the interaction contains more information than either variable individually.


What the Bot Should Measure

A serious experiment should capture every observation with timestamps.

At minimum:

  • market/token identifier
  • bid levels
  • ask levels
  • best bid
  • best ask
  • spread
  • book timestamp
  • local receive timestamp
  • TWAP value
  • price relative to TWAP
  • imbalance
  • subsequent price movement
  • subsequent spread
  • subsequent book depth

Polymarket's real-time documentation explicitly provides book timestamps and order-book levels, making event-time reconstruction an important part of the research pipeline. ([docs.polymarket.com][1])

Do not silently replace missing timestamps with local arrival time. Those are different measurements.


Why a Simple Backtest Can Lie

There are several traps.

Look-ahead bias

Do not calculate an imbalance using information that became available after the signal timestamp.

Snapshot bias

Sampling every second can miss short-lived order-book events.

Selection bias

A strategy tested only during active markets may behave differently in thin markets.

Survivorship bias

Do not analyze only markets that remained liquid enough to trade.

Overfitting

If the optimal imbalance threshold changes every time the dataset changes, the strategy may be fitting noise.

Most importantly, measure future movement conditional on the signal, not just whether a hypothetical trade would have made money.


What Most Traders Get Wrong

1. Large bids do not automatically mean bullish information.

Liquidity can disappear.

2. Imbalance is not momentum.

It measures displayed supply/demand conditions, not guaranteed future price direction.

3. TWAP is not a prediction oracle.

A TWAP is a reference constructed from prices over time. Being above or below it is contextual information, not proof of future movement.

4. A stronger signal can still produce worse execution.

If everyone reacts to the same visible imbalance, the price may move before execution.

5. The best signal may be the disappearance of imbalance.

A rapidly collapsing bid wall after persistent positive imbalance could contain more information than the original imbalance itself.


Engineering Architecture

A practical research architecture is:

flowchart LR
    BOOK[Polymarket Order Book] --> STATE[Book State]
    TWAP[TWAP Reference] --> SIGNAL[Signal Engine]
    STATE --> OBI[Multi-Level Imbalance]
    OBI --> SIGNAL
    SIGNAL --> PERSIST[Persistence Filter]
    PERSIST --> EXEC[Execution Layer]
    EXEC --> MONITOR[Execution + Risk Monitor]
    STATE --> STORE[Event Store]
    SIGNAL --> STORE

The important architectural decision is separating data reconstruction from signal generation.

Store raw events first.

Generate signals from reconstructed state afterward.

That allows the same dataset to be replayed with different imbalance definitions without collecting everything again.


Advanced Insight: Imbalance Should Be Conditional

The strongest research question is not:

“Does positive imbalance predict price?”

It is:

“Under what TWAP and liquidity conditions does positive imbalance contain incremental information?”

For example, divide observations into regimes:

  • price above TWAP / below TWAP
  • narrow spread / wide spread
  • high depth / low depth
  • persistent imbalance / transient imbalance

Then measure future returns or price changes separately.

This is much more informative than one global correlation.

Research on order-flow imbalance also suggests that depth matters and that multi-level information can improve explanatory power, reinforcing the idea that imbalance should not be treated as a single scalar detached from liquidity conditions. ([Taylor & Francis Online][3])


What This Means for Polymarket Developers

The real engineering opportunity is building a replayable microstructure dataset.

Capture the book.

Reconstruct its state.

Calculate imbalance continuously.

Align it with TWAP.

Measure persistence.

Then test what happened afterward.

Only after that should execution logic enter the system.

Polymarket's current real-time infrastructure provides book, price-change, trade, and related market events, making event-driven rather than polling-based research practical. ([docs.polymarket.com][1])

The deeper lesson is simple:

The useful signal is rarely “the order book is bullish.”

It is:

“The order book is persistently imbalanced, the market is positioned relative to TWAP in a compatible regime, liquidity remains present, and subsequent price behavior confirms the hypothesis.”

That is a researchable statement.

And unlike a generic buy/sell indicator, it can be measured, falsified, replayed, and improved.

Frequently Asked Questions

What is Polymarket TWAP order book imbalance?
It is a research concept combining a TWAP reference with the relative amount of displayed bid and ask liquidity in a Polymarket order book.

Is order book imbalance a guaranteed trading signal?
No. Displayed liquidity can change or disappear, and imbalance may reflect temporary market conditions.

Should imbalance use only the best bid and ask?
Not necessarily. Multi-level imbalance can provide a broader representation of displayed liquidity.

Why combine imbalance with TWAP?
TWAP provides temporal context, allowing imbalance to be evaluated differently depending on whether price is above or below the reference.

What should be tested first?
Test whether imbalance has incremental explanatory power after controlling for spread, depth, price/TWAP distance, and recent price movement.

Conclusion

A Polymarket TWAP order book imbalance bot should not begin with a trading rule.

It should begin with a measurement problem.

Does persistent displayed liquidity contain information beyond the current price and TWAP?

If the answer is yes, the next question is whether that information survives spreads, execution delay, liquidity changes, and adverse selection.

That is where the research becomes interesting.

来源:Google AI:DEV 作者专属(RSS) · dev.to