> ## Documentation Index
> Fetch the complete documentation index at: https://docs.codex.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Prediction Charts

> Learn how to render prediction market charts with outcome probabilities, event activity, and multi-market comparisons

In this recipe we'll show you how to fetch and render prediction market chart data at three levels: individual market outcome charts, event-level aggregated charts, and multi-market comparison charts within an event.

Prediction market charts differ from token charts: instead of a single price, you have dual outcome probabilities, bid/ask spreads, and market-level metrics like open interest. Three chart queries are available:

* **`predictionMarketBars`**: single market, per-outcome OHLC
* **`predictionEventBars`**: event-level aggregated volume/liquidity/OI
* **`predictionEventTopMarketsBars`**: multi-market probability comparison

All support resolutions: `min1`, `min5`, `min15`, `min30`, `hour1`, `hour4`, `hour12`, `day1`, `week1`.

## Step 1: Single Market Outcome Charts

The core chart for any prediction market detail page. It shows how each outcome's probability has moved over time with full OHLC data. Use [`predictionMarketBars`](/api-reference/queries/predictionmarketbars) to fetch per-outcome price, liquidity, bid/ask, and volume data.

<Info>
  You will need a market ID to fetch charts. Use [filterPredictionMarkets](/api-reference/queries/filterpredictionmarkets) to grab a market ID.
</Info>

<AccordionGroup>
  <Accordion title="Outcome probability chart with full OHLC data">
    [Test this query in the Explorer →](/explore)

    ```graphql theme={null} theme={null}
    query PredictionMarketBars {
      predictionMarketBars(
        input: {
          marketId: "yourMarketId"
          from: 1773100000
          to: 1773700000
          resolution: hour1
        }
      ) {
        marketId
        predictionMarket {
          id
          label
          question
          outcomeLabels
          eventLabel
        }
        bars {
          t
          volumeUsd
          volumeCollateralToken
          trades
          uniqueTraders
          openInterestUsd {
            o
            h
            l
            c
          }
          outcome0 {
            trades
            buys
            sells
            volumeUsd
            buyVolumeUsd
            sellVolumeUsd
            priceUsd {
              o
              h
              l
              c
            }
            priceCollateralToken {
              o
              h
              l
              c
            }
            liquidityCollateralToken {
              o
              h
              l
              c
            }
            bidCollateralToken {
              o
              h
              l
              c
            }
            askCollateralToken {
              o
              h
              l
              c
            }
          }
          outcome1 {
            trades
            buys
            sells
            volumeUsd
            buyVolumeUsd
            sellVolumeUsd
            priceUsd {
              o
              h
              l
              c
            }
            priceCollateralToken {
              o
              h
              l
              c
            }
            liquidityCollateralToken {
              o
              h
              l
              c
            }
            bidCollateralToken {
              o
              h
              l
              c
            }
            askCollateralToken {
              o
              h
              l
              c
            }
          }
        }
      }
    }
    ```
  </Accordion>
</AccordionGroup>

**Chart types you can render from this data:**

**Outcome probability (candlestick or line):**

* Use `outcome0.priceCollateralToken` / `outcome1.priceCollateralToken` for OHLC candlestick charts
* The close price (`c`) represents the current implied probability (e.g., 0.65 = 65%)
* For a simpler line chart, just plot the `c` (close) values over time

**Bid/Ask spread (dual line):**

* Plot `outcome0.bidCollateralToken.c` and `outcome0.askCollateralToken.c` as two lines
* The gap between them is the spread. Tighter = more liquid/efficient market

**Volume (bar chart):**

* `volumeUsd` at the market level for total volume per bar
* Per-outcome volume with `outcome0.volumeUsd` / `outcome1.volumeUsd`
* Buy/sell breakdown with `buyVolumeUsd` / `sellVolumeUsd`

**Open interest (OHLC):**

* `openInterestUsd` at the market level shows total capital at risk

**Activity (line):**

* `trades` and `uniqueTraders` per bar

<Info>
  **Additional parameters:**

  * `countback`: Instead of `from`, specify "give me the last N bars from `to`", which is useful for "show last 100 candles"
  * `removeEmptyBars`: Skip bars with no trading activity (useful for illiquid markets)
</Info>

## Step 2: Multi-Market Probability Comparison

The signature prediction market chart: multiple outcome lines on one chart, like Polymarket's multi-candidate probability view. Use [`predictionEventTopMarketsBars`](/api-reference/queries/predictioneventtopmarketsbars) to get bars for the top markets in an event in a single request.

<AccordionGroup>
  <Accordion title="Top 5 markets by volume">
    [Test this query in the Explorer →](/explore)

    ```graphql theme={null} theme={null}
    query TopMarketsByVolume {
      predictionEventTopMarketsBars(
        input: {
          eventId: "yourEventId"
          from: 1773100000
          to: 1773700000
          resolution: hour1
          limit: 5
          rankBy: "volumeUsd1w"
          rankDirection: "DESC"
        }
      ) {
        eventId
        predictionEvent {
          id
          question
        }
        marketBars {
          marketId
          predictionMarket {
            id
            label
            outcomeLabels
          }
          bars {
            t
            outcome0 {
              priceCollateralToken {
                o
                h
                l
                c
              }
              volumeUsd
              trades
            }
            outcome1 {
              priceCollateralToken {
                o
                h
                l
                c
              }
            }
            openInterestUsd {
              o
              h
              l
              c
            }
            volumeUsd
          }
        }
      }
    }
    ```
  </Accordion>
</AccordionGroup>

**How to use this data:**

* Returns OHLC bars for up to 10 markets in a single request
* Each market in `marketBars` has its own `bars` array
* Plot `outcome0.priceCollateralToken.c` for each market as a separate colored line, labeled with `predictionMarket.label`
* **Ranking options:** `rankBy` for market-level attributes (`volumeUsd1w`, `trendingScore24h`, etc.) or `rankByOutcome` + `rankByOutcomeAttribute` for outcome-level (`bestAskCT`, `lastPriceUsd`, etc.)
* `marketIds` overrides ranking. Use it when you want specific markets regardless of rank

## Step 3: Event-Level Aggregated Charts

Shows aggregated activity across ALL markets in an event. This is useful for volume, liquidity, and open interest charts at the event level. Use [`predictionEventBars`](/api-reference/queries/predictioneventbars).

<AccordionGroup>
  <Accordion title="Event-level volume, liquidity, and open interest">
    [Test this query in the Explorer →](/explore)

    ```graphql theme={null} theme={null}
    query PredictionEventBars {
      predictionEventBars(
        input: {
          eventId: "yourEventId"
          from: 1773100000
          to: 1773700000
          resolution: "day1"
        }
      ) {
        eventId
        predictionEvent {
          id
          question
          marketIds
        }
        bars {
          t
          volumeUsd
          buyVolumeUsd
          sellVolumeUsd
          totalVolumeUsd
          trades
          uniqueTraders
          liquidityUsd {
            o
            h
            l
            c
          }
          openInterestUsd {
            o
            h
            l
            c
          }
        }
      }
    }
    ```
  </Accordion>
</AccordionGroup>

**Chart types from this data:**

* **Volume bar chart:** `volumeUsd` per bar, optionally split into `buyVolumeUsd` / `sellVolumeUsd` for buy/sell pressure visualization
* **Liquidity area chart:** `liquidityUsd` OHLC. Use `c` for a simple line, or shade between `l` and `h` for a range
* **Open interest line:** `openInterestUsd` OHLC. Shows total capital committed across all markets
* **Activity line:** `trades` and `uniqueTraders` per bar
* **Cumulative volume:** `totalVolumeUsd` is the running total

This query does NOT include per-outcome price data. Use `predictionEventTopMarketsBars` for that.

## Step 4: Rendering with a Chart Library

Transform the API response into chart-ready data. This approach works with any library (lightweight-charts, TradingView, Chart.js, etc.):

**Candlestick data (for outcome prices):**

```typescript theme={null}
// Transform outcome OHLC bars for a candlestick chart
const candlestickData = bars.map(bar => ({
  time: bar.t,   // unix timestamp
  open: parseFloat(bar.outcome0.priceCollateralToken.o),
  high: parseFloat(bar.outcome0.priceCollateralToken.h),
  low: parseFloat(bar.outcome0.priceCollateralToken.l),
  close: parseFloat(bar.outcome0.priceCollateralToken.c),
}));
```

**Multi-line data (for probability comparison):**

```typescript theme={null}
// Transform multiple markets into line series
const series = marketBars.map(mb => ({
  label: mb.predictionMarket.label,
  data: mb.bars.map(bar => ({
    time: bar.t,
    value: parseFloat(bar.outcome0.priceCollateralToken.c),
  })),
}));
```

**Volume bars:**

```typescript theme={null}
// Transform volume data for bar chart overlay
const volumeData = bars.map(bar => ({
  time: bar.t,
  value: parseFloat(bar.volumeUsd),
  color: parseFloat(bar.buyVolumeUsd) > parseFloat(bar.sellVolumeUsd)
    ? '#22c55e'  // green = net buying
    : '#ef4444', // red = net selling
}));
```

## Step 5: Resolution Selection

| Time range displayed | Recommended resolution |
| -------------------- | ---------------------- |
| Last hour            | min1                   |
| Last 4 hours         | min5                   |
| Last 24 hours        | min15 or min30         |
| Last week            | hour1                  |
| Last month           | hour4 or hour12        |
| Last 3 months        | day1                   |
| All time             | day1 or week1          |

* Higher resolutions (min1, min5) give more granular data but return more bars
* For markets with low activity, use `removeEmptyBars: true` to skip empty candles
* Use `countback` instead of `from` when you want a fixed number of bars regardless of time range

## Putting It All Together

Recommended chart layout for a prediction event page:

1. **Top chart:** Multi-market probability lines via `predictionEventTopMarketsBars`, the hero visualization
2. **Below:** Volume bar chart via `predictionEventBars`, showing overall event activity
3. **Drill-down:** When user clicks a specific market, show its detailed OHLC chart via `predictionMarketBars` with metric selector (price, liquidity, bid/ask, volume, OI)

All three queries accept the same resolution values, so a single resolution picker can control all charts on the page.

<Tip>
  **Collateral Token (CT) vs USD:** CT values (e.g., `priceCollateralToken`) are preferred for prediction markets since the collateral is typically a stablecoin. USD values include exchange rate fluctuations.

  **Implied probability:** For stablecoin-collateral markets, `priceCollateralToken.c = 0.65` means the market implies a 65% probability.

  **OHLC fields:** `o` = open, `h` = high, `l` = low, `c` = close. Standard candlestick format. All values are strings that should be parsed to floats.

  **Timestamps:** The `t` field is a unix timestamp in seconds. Chart libraries may need milliseconds, so multiply by 1000.

  **Empty bars:** Illiquid markets may have bars with no trades. Use `removeEmptyBars` to skip them, or fill forward with the previous bar's close value for continuous lines.
</Tip>

Check out the related chart endpoints in their API reference pages:

* [predictionMarketBars](/api-reference/queries/predictionmarketbars)
* [predictionEventBars](/api-reference/queries/predictioneventbars)
* [predictionEventTopMarketsBars](/api-reference/queries/predictioneventtopmarketsbars)
