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

# DEX 거래

> DEX 거래 데이터에 대한 쿼리 예제

**DEXTrades** Cube에는 DEX 스왑 이벤트가 거래 단위로 들어 있으며, 제공되는 데이터 중 가장 세분화된 거래 데이터입니다. 개별 거래 조회, 지갑 활동 분석, 토큰 가격 추적, 상위 트레이더 찾기 등에 사용할 수 있습니다.

<Note>
  아래 예시는 모두 `network: sol`(Solana)을 사용합니다. 다른 지원 체인은 `eth`, `bsc`, `polygon` 등으로 바꿉니다.
</Note>

***

## 최신 DEX 거래를 어떻게 가져오나요?

Solana에서 가장 최근 DEX 거래 10건을 가져옵니다. 블록 정보, 트랜잭션 해시, 매수/매도 상세, DEX 프로토콜을 포함합니다.

```graphql theme={null}
query {
  Solana {
    DEXTrades(
      limit: {count: 10}
      orderBy: {descending: Block_Time}
    ) {
      Block { Time, Slot }
      Transaction { Hash }
      Trade {
        Buy {
          Currency { MintAddress }
          Amount
          PriceInUSD
          Account { Owner }
        }
        Sell {
          Currency { MintAddress }
          Amount
          Account { Owner }
        }
        Dex { ProgramAddress, ProtocolName }
      }
      Pool { Address }
    }
  }
}
```

<Tip>
  [GraphQL IDE에서 열기](https://ide.chainstream.io) — 위 쿼리를 붙여넣어 자동 완성과 스키마 탐색으로 대화형 실행할 수 있습니다.
</Tip>

<AccordionGroup>
  <Accordion title="주요 필드">
    | 필드                               | 설명                                 |
    | :------------------------------- | :--------------------------------- |
    | `Block.Time`                     | 블록 타임스탬프(ISO 8601)                 |
    | `Block.Slot`                     | Solana 슬롯 번호(Solana 전용)            |
    | `Transaction.Hash`               | 온체인 트랜잭션 해시 — 익스플로러에서 해당 tx 조회에 사용 |
    | `Trade.Buy.Currency.MintAddress` | 매수 자산의 토큰 주소                       |
    | `Trade.Buy.PriceInUSD`           | 거래 시점 매수 토큰의 USD 가격                |
    | `Trade.Buy.Account.Owner`        | 매수자 지갑 주소                          |
    | `Trade.Dex.ProtocolName`         | DEX 이름(예: Raydium, Orca, Jupiter)  |
    | `Pool.Address`                   | 거래가 실행된 유동성 풀 주소                   |
  </Accordion>

  <Accordion title="맞춤 설정 팁">
    * **체인 전환**: `network: sol`을 `network: eth`, `network: bsc`, `network: polygon`으로 변경
    * **결과 수 늘리기**: `count: 10`을 최대 `10000`까지 변경
    * **시간 필터 추가**: `where: {Block: {Time: {after: "2025-03-01T00:00:00Z"}}}`로 기간 한정
    * **DEX로 필터**: `where: {Trade: {Dex: {ProtocolName: {is: "Raydium"}}}}`로 특정 프로토콜만
  </Accordion>
</AccordionGroup>

***

## 특정 토큰의 거래를 어떻게 가져오나요?

`tokenAddress` 셀렉터로 토큰 주소를 넘겨 해당 토큰의 거래를 조회합니다.

```graphql theme={null}
query {
  Solana {
    DEXTrades(
      limit: {count: 10}
      tokenAddress: {is: "TOKEN_ADDRESS"}
      orderBy: {descending: Block_Time}
    ) {
      Block { Time }
      Trade {
        Buy { Amount, PriceInUSD, Account { Owner } }
        Sell { Currency { MintAddress }, Amount }
        Dex { ProtocolName }
      }
      Pool { Address }
    }
  }
}
```

<Tip>
  `TOKEN_ADDRESS`를 실제 토큰 mint 주소로 바꿉니다(예: Solana USDC는 `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`). 이름으로 주소를 찾으려면 [토큰 메타데이터](/ko/graphql/examples/ohlc-stats#how-do-i-look-up-token-information)를 참고하세요.
</Tip>

<AccordionGroup>
  <Accordion title="주요 필드">
    | 필드                                | 설명                    |
    | :-------------------------------- | :-------------------- |
    | `Trade.Buy.Amount`                | 매수한 토큰 수량             |
    | `Trade.Buy.PriceInUSD`            | 거래 시점 토큰당 가격          |
    | `Trade.Buy.Account.Owner`         | 매수를 실행한 지갑            |
    | `Trade.Sell.Currency.MintAddress` | 매도 자산의 토큰 주소(페어의 반대쪽) |
    | `Trade.Dex.ProtocolName`          | DEX 프로토콜 이름           |
  </Accordion>

  <Accordion title="맞춤 설정 팁">
    * **최소 금액으로 필터**: `where: {Trade: {Buy: {Amount: {gt: 1000}}}}`로 대량 거래만
    * **가격 구간**: `where: {Trade: {Buy: {PriceInUSD: {gte: 0.001, lte: 1.0}}}}`로 구간 한정
    * **의심 거래 제외**: `IsSuspect = false` 필터가 기본 적용되어 봇/MEV 거래는 이미 제외됨
  </Accordion>
</AccordionGroup>

***

## 지갑의 모든 거래를 어떻게 가져오나요?

특정 지갑 주소의 모든 거래를 조회합니다.

```graphql theme={null}
query {
  Solana {
    DEXTrades(
      limit: {count: 20}
      walletAddress: {is: "WALLET_ADDRESS"}
      orderBy: {descending: Block_Time}
    ) {
      Block { Time }
      Trade {
        Buy { Currency { MintAddress }, Amount, PriceInUSD }
        Sell { Currency { MintAddress }, Amount }
        Dex { ProtocolName }
      }
      Transaction { Hash, FeeInNative }
    }
  }
}
```

<Info>
  `walletAddress` 셀렉터는 해당 지갑이 매수자이거나 매도자인 거래와 일치합니다.
</Info>

<AccordionGroup>
  <Accordion title="주요 필드">
    | 필드                                | 설명                               |
    | :-------------------------------- | :------------------------------- |
    | `Trade.Buy.Currency.MintAddress`  | 매수한 토큰                           |
    | `Trade.Sell.Currency.MintAddress` | 매도한 토큰                           |
    | `Transaction.FeeInNative`         | 네이티브 토큰 단위 가스 수수료(Solana에서는 SOL) |
  </Accordion>

  <Accordion title="맞춤 설정 팁">
    * **단일 토큰만**: `tokenAddress: {is: "TOKEN_ADDRESS"}`와 함께 사용해 해당 지갑의 특정 토큰 거래만
    * **시간 구간**: `where: {Block: {Time: {after: "2025-03-01T00:00:00Z"}}}`로 최근 거래만
    * **limit 늘리기**: `count: 100`으로 더 많은 이력(최대 10,000)
  </Accordion>
</AccordionGroup>

***

## 토큰의 현재 가격을 어떻게 가져오나요?

가장 최근의 비의심(non-suspect) 거래에서 토큰의 최신 가격을 가져옵니다.

```graphql theme={null}
query {
  Solana {
    DEXTrades(
      limit: {count: 1}
      tokenAddress: {is: "TOKEN_ADDRESS"}
      where: {IsSuspect: {eq: false}}
      orderBy: {descending: Block_Time}
    ) {
      Trade {
        Buy { PriceInUSD, PriceInNative }
      }
      Block { Time }
    }
  }
}
```

<AccordionGroup>
  <Accordion title="주요 필드">
    | 필드                        | 설명                              |
    | :------------------------ | :------------------------------ |
    | `Trade.Buy.PriceInUSD`    | 가장 최근 거래 기준 USD 가격              |
    | `Trade.Buy.PriceInNative` | 체인 네이티브 토큰(SOL, ETH, BNB) 단위 가격 |
    | `Block.Time`              | 거래 타임스탬프 — 가격이 얼마나 최신인지 표시      |
  </Accordion>

  <Accordion title="맞춤 설정 팁">
    * **여러 시점 가격**: `count`를 늘려 최근 가격 시리즈를 가져와 평균 등에 활용
    * **크로스 체인**: `network: eth`로 Ethereum에서 동일 토큰 가격 조회(해당 체인에 존재할 경우)
  </Accordion>
</AccordionGroup>

<Tip>
  시간에 따른 안정적인 토큰 가격이 필요하면 [Pairs](/ko/graphql/examples/ohlc-stats#how-do-i-get-k-line-ohlc-candlestick-data) Cube 사용을 고려하세요 — 분 단위 시가/고가/저가/종가가 미리 계산된 캔들 데이터를 제공합니다.
</Tip>

***

## 토큰의 상위 트레이더를 어떻게 찾나요?

집계로 토큰의 상위 트레이더를 찾습니다. 이 쿼리는 거래를 매수 지갑별로 묶어 총 매수 횟수와 거래량을 반환합니다.

```graphql theme={null}
query {
  Solana {
    DEXTrades(
      limit: {count: 100}
      tokenAddress: {is: "TOKEN_ADDRESS"}
      where: {IsSuspect: {eq: false}}
    ) {
      Trade {
        Buy {
          Account { Owner }
          Amount
          PriceInUSD
        }
      }
      count
      sum(of: Trade_Buy_Amount)
    }
  }
}
```

<AccordionGroup>
  <Accordion title="주요 필드">
    | 필드                          | 설명               |
    | :-------------------------- | :--------------- |
    | `Trade.Buy.Account.Owner`   | 지갑 주소(그룹 키)      |
    | `count`                     | 해당 지갑의 거래 수      |
    | `sum(of: Trade_Buy_Amount)` | 해당 지갑이 매수한 총 토큰량 |
  </Accordion>

  <Accordion title="맞춤 설정 팁">
    * **거래량 기준 정렬**: 결과는 차원 필드별로 그룹화됨 — 차원을 줄이면 더 상위 수준 집계
    * **기간 한정 리더보드**: `where: {Block: {Time: {after: "2025-03-01T00:00:00Z"}}}` 추가
    * **소액 거래 제외**: `where`에 `Trade: {Buy: {Amount: {gt: 100}}}` 추가
  </Accordion>
</AccordionGroup>

<Info>
  메트릭 필드(`count`, `sum`)와 차원 필드를 함께 선택하면 API가 선택한 차원으로 결과를 자동 그룹화합니다. 자세한 내용은 [Metrics & Aggregation](/ko/graphql/schema/metrics-aggregation)을 참고하세요.
</Info>

***

## 멀티체인 예시

동일한 쿼리는 지원되는 모든 체인에서 동작합니다 — `network` 파라미터만 바꾸면 됩니다.

<Tabs>
  <Tab title="Solana">
    ```graphql theme={null}
    query {
      Solana {
        DEXTrades(
          limit: {count: 5}
          orderBy: {descending: Block_Time}
        ) {
          Block { Time, Slot }
          Trade {
            Buy { Currency { MintAddress }, PriceInUSD }
            Dex { ProtocolName }
          }
        }
      }
    }
    ```
  </Tab>

  <Tab title="Ethereum">
    ```graphql theme={null}
    query {
      EVM(network: eth) {
        DEXTrades(
          limit: {count: 5}
          orderBy: {descending: Block_Time}
        ) {
          Block { Time, Height }
          Trade {
            Buy { Currency { MintAddress }, PriceInUSD }
            Dex { ProtocolName }
          }
        }
      }
    }
    ```
  </Tab>

  <Tab title="BSC">
    ```graphql theme={null}
    query {
      EVM(network: bsc) {
        DEXTrades(
          limit: {count: 5}
          orderBy: {descending: Block_Time}
        ) {
          Block { Time, Height }
          Trade {
            Buy { Currency { MintAddress }, PriceInUSD }
            Dex { ProtocolName }
          }
        }
      }
    }
    ```
  </Tab>
</Tabs>

***

## 다음 단계

<CardGroup cols={2}>
  <Card title="전송" icon="paper-plane" href="/ko/graphql/examples/transfers">
    온체인 토큰 전송 데이터를 조회합니다.
  </Card>

  <Card title="잔액 및 홀더" icon="wallet" href="/ko/graphql/examples/balance-holders">
    지갑 잔액, 잔액 이력, 상위 홀더를 조회합니다.
  </Card>

  <Card title="풀 및 유동성" icon="droplet" href="/ko/graphql/examples/pools-liquidity">
    DEX 풀과 유동성 데이터를 탐색합니다.
  </Card>

  <Card title="OHLC 및 통계" icon="chart-candlestick" href="/ko/graphql/examples/ohlc-stats">
    캔들 데이터, 거래 통계, 시가총액, 토큰 메타데이터를 가져옵니다.
  </Card>
</CardGroup>
