Metadata-Version: 2.5
Name: inflection-exchange
Version: 0.9.0
Summary: Python client for the Inflection exchange.
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Requires-Python: >=3.11
Requires-Dist: cryptography>=44
Requires-Dist: httpx>=0.28.1
Requires-Dist: pycryptodome>=3.23
Requires-Dist: websockets>=17.1
Description-Content-Type: text/markdown

# Inflection Python SDK

A Python client for the Inflection exchange. It authenticates with your API
key, keeps the connections open, streams market data, and tracks your orders so
you can place them and await the outcome.

## Install

```sh
pip install inflection-exchange
```

## Quick start

```python
import asyncio
from inflection_exchange import (
    BookLevel,
    ExchangeClient,
    MarketDataFeed,
    Outcome,
    Side,
)


async def main():
    async with (
        MarketDataFeed(series=["btc-updown-5m"], book_level=BookLevel.L1) as feed,
        ExchangeClient.from_secret_file("inflection-key-testnet.json") as client,
    ):
        market = feed.tradable_markets()[0]
        book = feed.books.get((market.market_id, Outcome.UP))
        print(market.slug, book)

        order = await client.place_limit(
            market.market_id, Outcome.UP, Side.BID, 4500, 100
        )
        await order.wait_accepted()
        print(order.status, order.filled_quantity)

        await client.cancel_all()


asyncio.run(main())
```

The client trades for the account its API key belongs to.

### Make a key and load it

Sign in to the app and open Settings > API keys. Choose New API key, give it
a label and choose Create. The app makes an API key and a trading key (the
key that signs orders, see "Trading keys" below), registers both
with your account, and shows one secret: a JSON object with `key_id`,
`account_id`, `private_key`, `trading_key`, `trading_key_expires_at_ms` and
`environment`. Choose Copy key, or download the secret as a file named like
`inflection-key-staging.json`. The app shows the secret once and cannot show
it again, because the exchange never sees the private keys. Anyone who has it
can trade on your account, so keep it like a password.

Save the file where your bot can read it, and keep it out of version control.
`ExchangeClient.from_secret_file` reads it and connects with no other setup,
as in the quick start above:

```python
client = ExchangeClient.from_secret_file("inflection-key-staging.json")
```

Or put the whole secret on one line in the variable `INFLECTION_SECRET`, for
example as a line of a `.env` file that your process manager loads, and call
`ExchangeClient.from_secret_env()`:

```sh
INFLECTION_SECRET='{"key_id": "...", "account_id": 7, "private_key": "...", ...}'
```

```python
client = ExchangeClient.from_secret_env()
client = ExchangeClient.from_secret(secret_text)  # the same, from text you hold
```

The loader raises `InvalidSecret`, and makes no client, when the file is
missing, the text is not valid JSON, it lacks `key_id`, `account_id`,
`private_key` or `trading_key`, it holds a key that does not load, it names a
trading key that has ended (or ends within seconds), or it was made for
another environment than the exchange says it is. The last two checks run
only when the secret has `trading_key_expires_at_ms` and `environment`; a
secret from another setup script may not. The message names the problem
(for an environment, both names) and never holds any of the secret's text.

A secret made before 0.9.0 names the trading key `session_key` and its end
`session_key_expires_at_ms`. The loader refuses it with `InvalidSecret`, which
says the secret was made before 0.9.0: make a new key in Settings > API keys.

### Which exchange the client signs for

A client does not guess its environment from the address. When you make one,
it asks the exchange once: `GET /api/user/environment` answers with the
environment (`local`, `staging`, `testnet` or `prod`), the chain id and the
vault. The client signs in the domain of that chain and vault, so a client
aimed at a staging host signs for staging, and for the vault that staging has
now. The answer is on `client.environment`. The request is blocking and runs
before anything is signed.

The SDK reads the answer over https only, except for an exchange on this
machine (`localhost`, `127.0.0.1` or `::1`). It refuses an answer that breaks
the chain rule: `prod` is on chain 8453 only, no other environment may be on
8453, and a chain the SDK does not know is refused. It pins prod's vault, and
no mainnet vault exists yet, so it refuses `prod` with an error that says so.
These raise `EnvironmentRefused`. An exchange that does not answer raises
`EnvironmentUnavailable`.

To make many clients with one request, fetch it once and give them the
config:

```python
config = ExchangeConfig(
    base_url="https://staging.example.com"
).with_environment_fetched()
clients = [ExchangeClient.from_secret_file(path, exchange=config) for path in paths]
```

The trading key ends at `trading_key_expires_at_ms`, and the client never
renews it: after that the exchange refuses every order with
`session_key_expired` (`RejectReason.TRADING_KEY_EXPIRED`), and you make a new
key in the app.

If you have a key id and its `.pem` file from elsewhere, pass them to
`ExchangeClient("your-key-id", "inflection-bot.pem")`. That client makes its
own trading key, as described under "Trading keys". See the
[API keys guide](https://inflection.exchange/docs/guides/api-keys/).

`ExchangeClient` signs the order socket's handshake with the key. To call the
account API yourself, sign each request the same way:

```python
from inflection_exchange import ApiKey

key = ApiKey("your-key-id", "inflection-bot.pem")
path = "/api/trading/accounts/7/balance"
httpx.get("https://inflection.exchange" + path, headers=key.sign("GET", path))
```

For a request with a body, also give the exact bytes that you send:
`key.sign("POST", path, body)`.

A signature is good for 30 seconds, so keep your clock in sync. If the
exchange refuses the key (a wrong id, a revoked key, or a clock that is off),
the client raises instead of retrying.

### When the exchange is starting

While the exchange starts, it refuses a new connection with "Exchange
starting. Try again." The client tries again, and `async with` keeps waiting
past `connect_timeout_s` meanwhile. If the exchange has not come back 5
minutes after the first refusal, the client raises `ExchangeDidNotComeBack`.
A connection the exchange accepts starts the 5 minutes over.

The SDK connects to `https://inflection.exchange`. To use another exchange,
such as a staging or a local one, give an `ExchangeConfig`. A URL that you do
not give follows `base_url` or `base_ws_url`. The client then asks that
exchange which environment it signs for, as described above:

```python
from inflection_exchange import ExchangeConfig

local = ExchangeConfig(
    base_url="http://localhost:5173",
    base_ws_url="ws://localhost:5173",
)
client = ExchangeClient("your-key-id", "inflection-bot.pem", exchange=local)
```

## Trading keys

Every place, modify and cancel carries a signature from a trading key. A
trading key is a P-256 key pair. It is not your API key. The exchange refuses
an order without a signature with `signature_required`.

`ExchangeClient` makes its own trading key when it connects, and registers it
with your API key. The key lasts 24 hours. When less than an hour is left, the
client registers a new key and revokes the old one. Leaving `async with`
revokes the key. If the exchange refuses a message because it does not know
the key, or because the key has expired, the client registers a new key and
sends the message again, one time. A signed message carries no time: the
key's expiry is set on the exchange's clock, which the client gets when it
connects.

To sign with a key that you registered, put its private number in a file as
64 hex digits. The client does not renew or revoke this key:

```python
client = ExchangeClient.with_trading_key_file(
    "your-key-id", "inflection-bot.pem", "trading-key.hex"
)
```

If your account has a linked wallet, each trading key needs a grant from the
wallet, and the client cannot make one. The app's Settings > API keys asks
the wallet for the grant when it makes a key, so load that key with
`from_secret_file` or `from_secret_env` (see "Make a key and load it" above). To register a key
yourself, with its grant, follow the
[signing guide](https://inflection.exchange/docs/guides/signing-orders/) and
load it from a file.

## Units

| Thing    | Unit          | Notes                                                                                      |
| -------- | ------------- | ------------------------------------------------------------------------------------------ |
| Price    | basis points  | `10_000` = $1 = 100%. Limit prices go from 100 to 9900 in steps of 100.                    |
| Quantity | lots          | 100 lots = 1 share. A winning share pays $1.                                               |
| Outcome  | `up` / `down` | Every market is binary. Buying `down` at p is the same order as selling `up` at 10000 − p. |

A market takes orders from the moment it is listed. While its window hasn't
started it is `open` and has no strike yet. Once the window starts it is
`live`, and the strike is known. The market is `closed` when the window ends,
and at that point the exchange cancels every order still resting in it. It is
`settled` once its outcome is recorded and paid out. `MarketStatus` names the
four.

NVDA and WTI windows trade only while their home exchange is open: NASDAQ for
NVDA, CME for WTI. Bitcoin trades around the clock. A window that won't trade
is never listed. `list_series` says when a closed series opens next:

```python
from inflection_exchange import list_series

for series in await list_series():
    print(series.series, series.next_open_ms)  # None while it trades
```

## Orders

Orders default to **good-till-cancelled**. Market orders are the exception:
they default to **immediate-or-cancel**, because a market order can't rest on
the book.

```python
order = await client.place_limit(market_id, Outcome.UP, Side.BID, 4500, 200)
order = await client.place_limit(
    market_id, "up", "bid", 4500, 200, expiry_ms=now_ms + 5 * 60_000
)  # good-till-date
order = await client.place_limit(market_id, "up", "ask", 5500, 200, post_only=True)
order = await client.place_market(market_id, "down", "bid", 100)  # IOC
order = await client.place_market(market_id, "down", "bid", 100, TimeInForce.FOK)

await client.modify(order, price_bps=4600)  # new price: goes to the back of the queue
await client.modify(order, quantity=100)  # smaller at the same price: keeps its place
await client.cancel(order)
await client.cancel_all()
```

The client draws each order's client order id at random, from 1 to
2^53 - 1. The exchange refuses a second place under an id that its market
has already seen, with `duplicate_client_order_id`.

### A market order's worst price

A market order fills at its worst price or better, and the rest is dropped
as unfilled (`market_no_liquidity`). You choose the worst price in one of
three ways:

| You pass               | The worst price                                                        |
| ---------------------- | ---------------------------------------------------------------------- |
| `worst_price_bps=5300` | 5300. Any whole bps from 1 to 9999; it need not be on the tick.        |
| `slippage_bps=500`     | The best price moved 5% of itself against you, if the client knows it. |
| nothing                | The same, with the default `slippage_bps` of 200 (2%).                 |
| `slippage_bps=None`    | No bound: the order takes any price.                                   |

The best price is the best ask for a buy and the best bid for a sell, in the
outcome you trade. A buy fills up to the best ask plus the slippage, rounded
up, and a sell down to the best bid less the slippage, rounded down. With a
best ask of 5100, a buy with the default slippage fills at up to 5202.

The client knows the best price only from a `MarketDataFeed` that follows the
market's book, which you give it as `client.market_data`. With no book data,
or nothing on the side the order takes, the order has no bound unless you
pass `worst_price_bps`:

```python
feed = MarketDataFeed(series=["btc-updown-5m"], book_level=BookLevel.L1)
async with feed, ExchangeClient("your-key-id", "inflection-bot.pem") as client:
    client.market_data = feed
    order = await client.place_market(market_id, "up", "bid", 100)
    order.worst_price_bps  # the price it was sent with, or None for no bound
```

### Fees

Each market has three fee settings, fixed when it is listed: on `Market`,
`taker_fee_rate_bps`, `maker_fee_rate_bps` and `maker_rebate_share_bps`. A
fill that takes liquidity pays the taker fee; a fill of a resting order gets
back a share of it. `fee_of_a_fill` gives the amount, in USDC base units:

```python
fee_of_a_fill(market, 5000, 10_000)  # 875000 at a taker rate of 350: $0.875
fee_of_a_fill(market, 5000, 10_000, Liquidity.MAKER)  # -175000: paid to you
```

Each place signs the most fee it accepts, `max_fee_bps`, and that signature
is your consent to the fee. By default the client signs the taker rate the
exchange lists for the market, which every fill at the market's fees is
within: it trusts the listed rate. It takes the rate from
`client.market_data`, or asks the markets service once for each market. To
cap your consent, pass `max_fee_bps` as a ceiling:

```python
await client.place_limit(market_id, Outcome.UP, Side.BID, 5000, 100, max_fee_bps=350)
```

An order in a market listed at a higher taker rate raises `InvalidOrder` and
is not sent. A listed rate that is not a whole number of bps from 0 to
10,000 raises `FeeRateRefused`. A market's fees never change, so a rate that
differs from the one the exchange gave before for the same market raises
`FeeRateRefused` too, at that place and every later one in the market. Each
`Fill` says what it paid in `fee` and whether your order took or made in
`liquidity`.

### Modifying an order

Each order has a `version`. A place is version 0, and each modify that the
exchange applies adds 1. A modify signs the order's version plus 1, so it
applies only to the order as you last saw it. If another modify is applied
first, the exchange refuses yours with `version_changed`, and the order
carries on as it is. That happens when you send a second modify before the
first one's `order_modified` arrives, or when another process modifies the
same order. Wait for `order.version` to change before you modify again.

Each call returns an `Order` that the SDK keeps up to date. You can await it,
or just read it later:

```python
try:
    await order.wait_accepted()  # raises OrderRejectedError if refused
except OrderRejectedError as e:
    if e.reason == RejectReason.INSUFFICIENT_COLLATERAL:
        ...

await order.wait_done()
order.status  # OrderStatus.FILLED, CANCELLED, UNFILLED, REJECTED, ...
order.filled_quantity  # lots filled so far
order.remaining_quantity  # lots still working on the book
order.reason  # why it was rejected, cancelled or unfilled
```

| Status      | Meaning                                                                                     |
| ----------- | ------------------------------------------------------------------------------------------- |
| `PENDING`   | Sent; the exchange hasn't replied yet.                                                      |
| `OPEN`      | Accepted and working. It may be partly filled.                                              |
| `FILLED`    | Completely filled.                                                                          |
| `CANCELLED` | Cancelled. `reason` says why: `client_request`, `expired`, `market_closed` or `self_trade`. |
| `UNFILLED`  | An IOC or market order's remainder was dropped. It may have partly filled first.            |
| `REJECTED`  | Refused. `reason` is a `RejectReason`.                                                      |
| `UNKNOWN`   | Finished while you were disconnected. Your fills say what happened.                         |

`client.orders` holds your live orders. On reconnect it is rebuilt from the
exchange's list of resting orders, so it includes orders from earlier runs.

**Orders are checked before they're sent.** An order the exchange would
certainly refuse raises `InvalidOrder` without being sent: a price that's off
the tick or outside 100–9900, a quantity that isn't a positive whole number
of lots, a resting market order, a worst price outside 1–9999, or a GTD
expiry less than 4 seconds ahead on the exchange's clock.

**The SDK doesn't track positions or P&L.** It passes every fill to you
(`on_fill`), so you can keep whatever view you need. The exchange's account
API holds the authoritative positions and balances.

### Cancel on disconnect

A bot can ask the exchange to cancel the account's resting orders when the
order socket ends:

```python
async with ExchangeClient(
    "your-key-id", "inflection-bot.pem", cancel_on_disconnect=True
) as client:
    assert client.cancel_on_disconnect  # what the exchange said; check it
```

`client.cancel_on_disconnect` is `True` once the exchange has armed the
current socket, and the client logs a warning if you asked and it did not.
When an armed socket ends (you leave the `async with`, the connection drops, or
the exchange drops it for not answering), the exchange cancels every resting
order of the account, including orders placed from other connections and the
website. Each is cancelled with `CancelReason.DISCONNECTED`. The client that
reconnects after a drop finds those orders gone and sees them as `UNKNOWN`.
Use a separate account if the bot should not touch other orders.

The exchange pings an armed socket about every 500 ms and drops it after about
1 second without an answer. The `websockets` library answers pings itself, but
only while your event loop runs, so don't block it for a second. A crash of the
exchange's gateway does not cancel anything.

## Market data

`MarketDataFeed` holds one connection to the public feed and keeps:

- `feed.markets`: the unfinished windows of what you follow, by id, oldest
  first. `feed.tradable_markets()` gives the ones taking orders.
- `feed.books[(market_id, outcome)]`: the best bid and ask (`BookTop`).
- `feed.depths[(market_id, outcome)]`: every price level, best first
  (`BookDepth`).

You must say what to follow. The exchange has no feed of everything. Pass
`series`, `markets`, or both, with at least one name or id. Also pass
`book_level`. If you leave one out, the constructor raises `ValueError` and
says what to pass.

A series is a line of windows, such as `btc-updown-5m`. Each new window of a
followed series arrives without a new request. `markets` follows markets by
id.

`book_level` is `BookLevel.L2` for every price level, or `BookLevel.L1` for the
best bid and ask only. With level 1, `feed.depths` stays empty.

Trades and status are opt-in. Pass `trades=True` to get `on_trade`. Pass
`status=True` to get `on_market_closed` and `on_market_settled`.

```python
from inflection_exchange import BookLevel, MarketDataFeed

feed = MarketDataFeed(
    series=["btc-updown-5m"], book_level=BookLevel.L2, trades=True, status=True
)
```

To follow every series, list them first with `list_series`. It names every
series, also one that is closed and has no windows yet.

```python
from inflection_exchange import BookLevel, MarketDataFeed, list_series

series = [s.series for s in await list_series()]
feed = MarketDataFeed(series=series, book_level=BookLevel.L1)
```

`list_markets` reads the filtered, paged market list. Always name a status: a
series with no status holds every window ever listed.

The feed fills `feed.markets` from the markets service when it starts. For
each series, it asks for the `open`, `live` and `closed` windows, one request
per status, and follows every page. For six series, that is 18 requests. If
the markets service refuses a name, `async with` raises with its reason. An
unknown series is one example.

After the start, the feed does not poll. It lists a series again only when the
socket names a market that `feed.markets` does not hold, such as a new
window. It lists only that market's series. It makes at most one list at a
time, and none within 5 seconds of the last. A market's `status` and `strike`
in `feed.markets` change only at those lists. A market that has left the list
loses its book. A feed that names only market ids lists once and does not list
again.

The server closes a connection that falls too far behind. So open one feed
per process, and share it between your bots.

### Books

The exchange sends Up prices only. The feed mirrors them. A Down bid at `p` is
an Up ask at `10_000 - p`. So `books` and `depths` hold both outcomes.

Each market counts its book changes: 1, 2, 3. The feed applies an update when
its number is one more than the last. It ignores an update at or below the
last. If a number is skipped, the feed drops that market's book and asks for a
new snapshot. It tells no listener about the dropped book.

`OrderBook` holds the Up book of one market with its sequence number.
`MarketDataApi.book` returns one.

### Listeners

To react to changes as they happen, add a listener with any of these methods:

```python
class Watcher:
    def on_book(self, book): ...
    def on_depth(self, depth): ...
    def on_trade(self, trade): ...  # public trades, anyone's
    def on_market_closed(self, market_id): ...  # trading has stopped
    def on_market_settled(self, market_id, outcome): ...  # a SettlementOutcome


feed.subscribe(Watcher())
```

`outcome` is `SettlementOutcome.UP` or `DOWN` for the winner. It is `VOID` when
no price could decide the market: every lot, Up or Down, then pays 5,000 units
instead of 10,000 for a winner, and your fills stand.

Your own order events work the same way. Set `client.listener` to an object
with `on_fill(fill)` and/or `on_order_event(event)`. Listeners are called as
messages arrive, so they should be quick; do slow work in your own tasks.

A `Trade` is one match. It has these fields:

| Field                         | Meaning                                                              |
| ----------------------------- | -------------------------------------------------------------------- |
| `trade_id`                    | Counts 1, 2, 3 within the market.                                    |
| `up_price_bps`                | The price of Up in the match.                                        |
| `quantity`                    | Lots.                                                                |
| `taker_outcome`, `taker_side` | What the order that took liquidity did: `up` or `down`, `buy` or `sell`. |
| `time_ms`                     | When the match happened, in epoch milliseconds.                      |
| `price_bps`                   | The taker's price in the outcome it traded.                          |

Down bought at an Up price of 6000 is Down bought at 4000.

### If the connection drops

The feed clears every book, waits a random time, and connects again. The wait
is random between half a limit and the limit. The limit starts at 1 second,
doubles after each failed try, and stops at 30 seconds. After it connects, the
feed subscribes again and gets new snapshots. The server also repeats the
status of a market that closed and has not settled. So `on_market_closed` can
fire twice for one market.

The feed does not replay trades that it missed. A jump in `trade_id` shows a
missed trade. Read the missed trades with `MarketDataApi.trades`.

### REST

`MarketDataApi` reads the same data without a socket:

```python
from inflection_exchange import MarketDataApi, Outcome

async with MarketDataApi() as api:
    summaries = await api.summary(series=["btc-updown-5m"])
    print(summaries[0].top(Outcome.DOWN))
    book = await api.book(summaries[0].market_id, depth=10)
    trades = await api.trades(summaries[0].market_id, limit=50)
    older = await api.trades(summaries[0].market_id, before=trades[-1].trade_id)
```

| Call      | Returns                                                                        |
| --------- | ------------------------------------------------------------------------------ |
| `summary` | The best bid and ask, last trade and volume of named markets or series.        |
| `book`    | The top `depth` levels of an open market, at most 50.                          |
| `trades`  | A market's trades, newest first, at most 1,000. It works for past markets.     |

If the server answers with an error, the call raises `MarketDataApiError`. It
holds `status_code` and `detail`. After a 503, `retry_after_s` says when to try
again.

## Development

```sh
uv sync
uv run pytest
```

`tests/fixtures/*.json` holds a sample of every message the exchange sends.
[test_fixtures.py](tests/test_fixtures.py) checks that the SDK can read all
of them. `tests/fixtures/signing_vectors.json` is a copy of the exchange's
signing vectors. [test_signing.py](tests/test_signing.py) checks every one.

To test a strategy without a network, build a feed with any series and book
level, set `feed.markets` yourself, and pass messages to `feed.apply()`. Use
the samples in `tests/fixtures/marketdata.json` as a guide to their shape.

## License

Apache License 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
