# Kaptra exchange API: order book, market data and bots

> REST and WebSocket market data, order placement with signed transactions, and a market-making example for the Kaptra order book.

The Kaptra exchange is on-chain. There are two ways to trade, and both settle in the same block:

- **Order book** (module `x/orderbook`): limit orders with price-time priority. Makers trade at their own price and pay no trading fee; the taker pays a 0.1% taker fee (a governance parameter) that goes to stakers. Every transaction also pays the usual network gas fee in KPTR.
- **Pools** (module `x/dex`): constant-product swaps, used by the [swap page](https://dex.kaptra.xyz).

Trading page: https://trade.kaptra.xyz · Block explorer: https://block.kaptra.xyz · Network parameters: [network.md](https://kaptra.xyz/docs/network.md)

There is no account, API key or custody. Market data is public; an order is a transaction that your own key signs.

## Markets and units

A market is `BASE-QUOTE`, for example `KPTR-USDC`. Quote denoms are listed by `GET https://api.kaptra.xyz/kaptra/orderbook/v1/params` (`quote_denoms`, strongest first): on the testnet `uusdc` (test USDC) then `ukptr`. A token is quoted in the strongest quote denom that is not itself, so the market is `KPTR-USDC`, never `USDC-KPTR`.

The market data API speaks **display units** (`price` = whole quote per whole base, `amount` = whole base tokens) and also returns the raw chain values (`price_raw` = quote base units per base unit, `amount_raw` = base units). Orders on chain always use raw values.

`price_raw = price × 10^(quote_decimals − base_decimals)`. For KPTR-USDC both have 6 decimals, so the two prices are equal.

## Market data (REST)

Base URL: `https://kaptra.xyz/api/v1` (also `https://trade.kaptra.xyz/api/v1`). Read-only, JSON, CORS open, rate limited per IP.

| Endpoint | What it returns |
|---|---|
| `GET /status` | chain id, indexed height, number of markets and trades |
| `GET /markets` | every market: last price, 24h change, high, low, volume, best bid/ask, pool price, decimals |
| `GET /ticker?market=KPTR-USDC` | the same for one market (without `market`: all) |
| `GET /orderbook?market=KPTR-USDC&depth=50` | price levels: `bids` from the highest price, `asks` from the lowest |
| `GET /trades?market=KPTR-USDC&limit=100&before=<id>` | latest trades, newest first; `owner=kptr1...` filters by maker or taker |
| `GET /candles?market=KPTR-USDC&interval=1m&limit=500&from=&to=` | OHLCV candles; intervals `1m 5m 15m 30m 1h 4h 1d 1w`; `from`/`to` in unix seconds |
| `GET /orders?owner=kptr1...&market=KPTR-USDC` | open orders of an address (from the chain) |

Trades include both order-book fills (`"source": "book"`) and pool swaps (`"source": "amm"`), so candles exist for every token that trades. `side` is the taker side.

```
curl -s 'https://kaptra.xyz/api/v1/orderbook?market=KPTR-USDC&depth=5'
{"market":"KPTR-USDC","height":1234,
 "bids":[{"price":"0.0989","amount":"2703.11","total":"267.45","orders":1,"price_raw":"0.0989","amount_raw":"2703110000"}],
 "asks":[{"price":"0.0997","amount":"1311.51","total":"130.81","orders":1,"price_raw":"0.0997","amount_raw":"1311510000"}]}
```

The same data is on chain, without the indexer: `GET https://api.kaptra.xyz/kaptra/orderbook/v1/book?base_denom=ukptr&quote_denom=uusdc&depth=50`, `/kaptra/orderbook/v1/markets`, `/kaptra/orderbook/v1/orders?owner=...`, `/kaptra/orderbook/v1/order/{id}`, and pools at `/kaptra/dex/v1/pools`.

## WebSocket

`wss://kaptra.xyz/ws` (also `wss://trade.kaptra.xyz/ws`). Send JSON, receive JSON:

```
{"op":"subscribe","channel":"orderbook","market":"KPTR-USDC"}
{"op":"subscribe","channel":"trades","market":"KPTR-USDC"}
{"op":"subscribe","channel":"ticker","market":"KPTR-USDC"}
{"op":"subscribe","channel":"candles","market":"KPTR-USDC","interval":"1m"}
{"op":"subscribe","channel":"blocks"}
{"op":"unsubscribe", ...same fields...}
{"op":"ping"}
```

Each subscription first gets a snapshot (`"snapshot": true` for trades and candles), then an update after every block that touches the market: `{"type":"orderbook","market":"KPTR-USDC","data":{bids,asks,height}}` (full top 50 levels), `{"type":"trades","data":[new trades]}`, `{"type":"ticker","data":{...}}`, `{"type":"candles","interval":"1m","data":[last two candles]}` (replace candles with the same `time`), `{"type":"block","height":...,"time":...}`. Blocks come about every 2 seconds. The server pings every 25 s; at most 50 subscriptions per connection.

## Placing and cancelling orders

Orders are Cosmos SDK messages. Sign them with any Cosmos library (CosmJS, cosmpy, the `kaptrad` CLI) and broadcast to `https://rpc.kaptra.xyz` or `https://api.kaptra.xyz`. Chain id `kaptra-testnet-1`, gas price `0.0025ukptr`.

`/kaptra.orderbook.v1.MsgPlaceOrder`

| Field | Meaning |
|---|---|
| `owner` | your `kptr1...` address (the signer) |
| `base_denom`, `quote_denom` | e.g. `ukptr`, `uusdc` |
| `side` | `SIDE_BUY` (1) spends quote, `SIDE_SELL` (2) spends base |
| `price` | raw price as a decimal (`cosmos.Dec`, 18 decimals; on the protobuf wire the integer `price × 10^18`) |
| `quantity` | base units (integer) |
| `time_in_force` | `TIME_IN_FORCE_GTC` (0, rests until cancelled), `TIME_IN_FORCE_IOC` (1, fill what you can now, return the rest: use it for market orders with a worst price), `TIME_IN_FORCE_POST_ONLY` (2, refused if it would trade at once) |

The order locks its funds at once (a buy locks `ceil(quantity × price)` quote, a sell locks `quantity` base) and trades immediately against the best opposite orders, at their prices. Unused funds come back. The response has `order_id`, `filled`, `quote_amount`, `fee` and `resting`.

`/kaptra.orderbook.v1.MsgCancelOrders`: `owner`, `order_ids` (list), or `all: true` with `base_denom`/`quote_denom` (or neither, for every market). Ids already filled are skipped. Put several messages in one transaction to replace a whole ladder of quotes atomically: cancel all, then place new orders.

Rules (governance parameters, see `/kaptra/orderbook/v1/params`): order value at least `min_notional` quote units (0.01 USDC), at most `max_open_orders` (200) resting orders per account, an incoming order fills at most `max_fills` (100) resting orders. Your own older order on the other side is cancelled instead of trading with you (no self-trade).

CLI:

```
kaptrad tx orderbook place ukptr uusdc buy 0.095 1000000000 --from mykey \
  --chain-id kaptra-testnet-1 --node https://rpc.kaptra.xyz:443 --gas auto --gas-adjustment 1.5 --gas-prices 0.0025ukptr
kaptrad tx orderbook cancel 12,13 --from mykey ...        # or: cancel 0 --all
kaptrad tx orderbook place ukptr uusdc sell 0.09 500000000 --time-in-force ioc --from mykey ...   # market sell, worst price 0.09
kaptrad query orderbook book ukptr uusdc --node https://rpc.kaptra.xyz:443
```

CosmJS (TypeScript): register the type and send it like any message.

```ts
import { DirectSecp256k1HdWallet, Registry } from "@cosmjs/proto-signing";
import { SigningStargateClient, GasPrice, defaultRegistryTypes } from "@cosmjs/stargate";
// MsgPlaceOrder generated from proto/kaptra/orderbook/v1/tx.proto (ts-proto or protobufjs)
const registry = new Registry([...defaultRegistryTypes, ["/kaptra.orderbook.v1.MsgPlaceOrder", MsgPlaceOrder]]);
const wallet = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, { prefix: "kptr" });
const [{ address }] = await wallet.getAccounts();
const client = await SigningStargateClient.connectWithSigner("https://rpc.kaptra.xyz", wallet,
  { registry, gasPrice: GasPrice.fromString("0.0025ukptr") });
await client.signAndBroadcast(address, [{ typeUrl: "/kaptra.orderbook.v1.MsgPlaceOrder", value: {
  owner: address, baseDenom: "ukptr", quoteDenom: "uusdc", side: 1,
  price: "95000000000000000" /* 0.095 × 10^18 */, quantity: "1000000000", timeInForce: 0 } }], "auto");
```

The web pages use a dependency-free encoder that you can copy: `apps/token-factory/kaptra-tx.js` (`OrderbookMsgs.place`, `OrderbookMsgs.cancel`) in the [repository](https://github.com/bjarnifridrik01-wq/kaptra).

## Market-making bot

`cmd/kaptra-mm` in the repository is a working example (Go, Cosmos SDK client). Every few seconds it cancels its ladder and places a new one around a fair price in one transaction, and a second account sometimes takes liquidity so that trades and candles appear. The fair price follows the pool of the pair when there is one. On the testnet it runs on the team's server and trades test tokens only.

```
go build -o kaptra-mm ./cmd/kaptra-mm
./kaptra-mm --node https://rpc.kaptra.xyz:443 --chain-id kaptra-testnet-1 --home ./mm-keys \
  --market ukptr,uusdc,0.10 --levels 8 --spread 0.004 --step 0.003 --size 2000
```

It creates two keys (`mm-maker`, `mm-taker`) in `./mm-keys`; send them test KPTR and USDC from the [faucet](https://kaptra.xyz/network/#faucet) or pass `--funder-home` with a funded keyring.

## Limits and status

Testnet: tokens have no value, the chain may be reset (the API then starts a new history). The market data service is open source (`cmd/kaptra-market`) and can be run next to any node: `kaptra-market --rpc http://127.0.0.1:26657 --rest http://127.0.0.1:1317 --listen 127.0.0.1:8090`.
