Metadata-Version: 2.4
Name: polymach
Version: 0.1.1
Summary: Python SDK for the PolyMach low-latency Polymarket engine
Project-URL: Homepage, https://polymach.io
Project-URL: Documentation, https://polymach.io/docs
Project-URL: Legal, https://polymach.io/legal
Project-URL: Releases, https://downloads.polymach.io/releases/latest/index.json
Author-email: PolyMach <hello@polymach.io>
License: MIT License
        
        Copyright (c) 2026 PolyMach
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: agents,low-latency,polymarket,prediction-markets,quant,trading
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: cryptography>=45.0.0
Requires-Dist: eth-account>=0.13.7
Requires-Dist: eth-utils>=5.3.1
Description-Content-Type: text/markdown

# PolyMach SDK

<p align="center">
  <img src="assets/polymach-banner.png" alt="PolyMach banner" width="100%">
</p>

`polymach` is the public Python SDK for the private optimized Rust PolyMach execution engine for [Polymarket](https://polymarket.com).

It is designed for persistent sessions driven by agentic, low-latency quantitative trading where every millisecond matters.

What it does:

- installs as a normal Python package with `uv add polymach`
- auto-downloads the correct signed runtime binary on first use
- verifies the release manifest and archive hash before launch
- caches the runtime locally
- talks to a persistent local session for low-latency calls

No local Rust toolchain or source checkout is required for normal use.

## Performance Highlights

Measured on March 8, 2026 on the live BTC 5-minute market against the official [`polymarket-cli`](https://github.com/Polymarket/polymarket-cli) from the same machine:

- quote path: **3554.7x faster** at p50
  - `PolyMach`: `0.022 ms`
  - `polymarket-cli` book call: `78.48 ms`
- midpoint path: **3801.1x faster** at p50
  - `PolyMach`: `0.020 ms`
  - `polymarket-cli` midpoint call: `76.70 ms`
- live discovery: **4.7x faster** at p50
  - `PolyMach`: `64.12 ms`
  - `polymarket-cli` composite: `300.46 ms`
- account-health-equivalent path: **5.0x faster** at p50
  - `PolyMach`: `54.84 ms`
  - `polymarket-cli` composite: `271.84 ms`
- order create: **6.6x faster** at p50
  - `PolyMach`: `28.60 ms`
  - `polymarket-cli` create call: `188.37 ms`
- order cancel: **4.4x faster** at p50
  - `PolyMach`: `28.43 ms`
  - `polymarket-cli` cancel call: `124.31 ms`
- stream cadence vs official polling: **1.5x faster** at p50
  - `PolyMach`: `51.15 ms`
  - `polymarket-cli` midpoint polling: `75.65 ms`

Correctness checks passed in that run:

- market metadata parity
- quote parity within tolerance
- balance parity within tolerance

This speedup goes far beyond “SDK vs CLI subprocess”. The backend itself is built around a warmed local Rust runtime with a persistent session, hot quote paths, websocket-driven data, prewarming, cached order metadata, and many runtime and micro-optimizations across critical paths.

*These benchmark numbers are a live snapshot from one host and network path.
Treat them as directional measurements of the current implementation, not as a
guaranteed venue-wide SLA.*

## Install

```bash
uv add polymach
```

Single-file agent-oriented reference:

- [`DOCUMENTATION.md`](DOCUMENTATION.md)
- [`LEGAL.md`](LEGAL.md)
- [`TERMS.md`](TERMS.md)
- [`PRIVACY.md`](PRIVACY.md)

## Supported Machines And Builds

The SDK bootstrap picks the best matching signed runtime artifact optimized for the current machine from the public release catalog.

PolyMach ships signed native builds for each supported target family rather than one lowest-common-denominator binary.

Current release targets:

- Linux `x86_64` with glibc baseline: `x86_64-unknown-linux-gnu-v2`
- Linux `x86_64` with glibc and AVX2-class CPUs: `x86_64-unknown-linux-gnu-v3`
- Linux `x86_64` with glibc and AVX-512-capable CPUs: `x86_64-unknown-linux-gnu-v4`
- Linux `aarch64` with glibc: `aarch64-unknown-linux-gnu`
- macOS `aarch64` native Apple Silicon: `aarch64-apple-darwin`

Selection rules:

- on Linux `x86_64`, the SDK detects the host CPU level and chooses the highest compatible build
- `v4` hosts can run `v4`, `v3`, or `v2`, but the SDK prefers `v4`
- `v3` hosts can run `v3` or `v2`, but not `v4`
- `v2` hosts use the broadest baseline build
- on Linux `aarch64`, the SDK selects the ARM64 Linux build
- on macOS `aarch64`, the SDK selects the native Apple Silicon build

These artifacts are built specifically for their target systems. Linux `x86_64` is intentionally split into multiple optimized CPU tiers instead of shipping one generic x86 binary for all machines.

You can also force a specific published artifact with `POLYMACH_ARTIFACT_ID`, for example:

```bash
export POLYMACH_ARTIFACT_ID=x86_64-unknown-linux-gnu-v2
```

If you run on a target outside the published release set, provide a compatible local runtime binary with `POLYMACH_BIN`.

## Recommended Payment Flow

A `polymach` machine license costs a flat 50 USDC per 30-day cycle per machine to use.
Agentic setup and payment is incredibly simple.

The recommended first-run flow is:

1. create the client
2. call `start()`
3. if no license exists yet, send the exact Polygon payment returned by the SDK
4. call `start(tx_hash=...)` to activate the machine license

```python
from polymach import PolyMach

engine = PolyMach()

start = engine.start()
if not start.ready:
    payment = start.payment
    print(payment.token_symbol, payment.amount_display)
    print(payment.token_address)
    raise SystemExit("Send the exact Polygon payment above, then call start(tx_hash=...)")

start = engine.start(tx_hash="0xYOUR_PAYMENT_TX_HASH")
print(start.license_status.valid)
```

Notes:

- `start()` auto-downloads the runtime if needed.
- The payment request is machine-specific.
- Follow the exact payment instructions returned by the SDK.
- After sending payment, allow up to 15 minutes for confirmation during Polygon network congestion before treating activation as stuck.
- If the payment is already broadcast, retry `start(tx_hash=...)` with the same transaction hash once the network catches up.
- Use `cycles=N` if you want to prepay multiple billing cycles in one transaction.

## Automated Payment Flow

If you want the SDK to submit the Polygon payment itself, use `pay_and_start()`.

```python
from polymach import LocalAccountSigner, PaymentPendingError, PolyMach

engine = PolyMach()
signer = LocalAccountSigner.from_private_key("0xYOUR_PAYMENT_WALLET_PRIVATE_KEY")

try:
    start = engine.pay_and_start(signer=signer)
except PaymentPendingError as exc:
    start = engine.start(tx_hash=exc.tx_hash)

print(start.license_status.valid)
```

Notes:

- The payment wallet must hold the payment token on Polygon and a small amount of POL for gas.
- Prefer `signer=...` over raw `private_key=...`.
- If the payment transaction is broadcast but public RPC confirmation polling times out, the SDK raises `PaymentPendingError` with a recoverable `tx_hash`.
- You can resume activation later with `start(tx_hash=...)`.
- You can also resume through the same helper with `pay_and_start(tx_hash="0x...")`.
- Optional stuck-pending controls:
  - `replacement_attempts`
  - `replacement_gas_bump_percent`

## Live Trading

To place live orders on Polymarket, set the live-trading gate and trading credentials before starting the runtime.

Venue availability is separate from SDK availability. Runtime bootstrap,
payment, and license activation can succeed even if Polymarket later blocks
trading from the current IP address, network, or jurisdiction. Verify venue
access from the actual deployment host before depending on live order flow.

Minimal environment for a normal EOA wallet:

```bash
export POLYMACH_LIVE_ENABLED=true
export POLYMACH_LIVE_ACK=I_UNDERSTAND_REAL_MONEY_RISK
export POLYMACH_POLYMARKET_PRIVATE_KEY=0xYOUR_TRADING_WALLET_PRIVATE_KEY
export POLYMACH_POLYMARKET_SIGNATURE_TYPE=0
```

Then:

```python
from polymach import PolyMach

engine = PolyMach()
engine.prewarm(["TOKEN_ID"])
print(engine.market.quote("TOKEN_ID"))
```

For live order placement, the important variables are:

- `POLYMACH_LIVE_ENABLED=true`
- `POLYMACH_LIVE_ACK=I_UNDERSTAND_REAL_MONEY_RISK`
- `POLYMACH_POLYMARKET_PRIVATE_KEY`
- `POLYMACH_POLYMARKET_SIGNATURE_TYPE`
  - `0` = EOA
  - `1` = proxy
  - `2` = Gnosis Safe
- `POLYMACH_POLYMARKET_FUNDER` if the signer and funded trading address differ

If you use Polymarket API credentials, set all three together:

- `POLYMACH_POLYMARKET_API_KEY`
- `POLYMACH_POLYMARKET_API_SECRET`
- `POLYMACH_POLYMARKET_API_PASSPHRASE`

## Environment Variables

Most users do not need to set anything just to install the SDK.

### Runtime And Bootstrap

- `POLYMACH_RELEASE_INDEX_URL`: explicit signed `index.json` URL
- `POLYMACH_RELEASE_BASE_URL`: custom release base; `"{version}"` is supported
- `POLYMACH_RELEASE_PUBLIC_KEY`: override the embedded release verification key
- `POLYMACH_BIN`: force a specific local runtime binary
- `POLYMACH_ARTIFACT_ID`: force a specific release artifact
- `POLYMACH_RELEASE_TOKEN`: optional bearer token for private/custom artifact mirrors
- `POLYMACH_PERSISTENT=0`: disable the persistent local session path

### License And Payment

- `POLYMACH_LICENSE_BASE_URL`: license/payment service base URL
- `POLYMACH_LICENSE_TOKEN`: optional bearer token for the license service
- `POLYMACH_POLYGON_RPC_URL`: primary Polygon RPC override
- `POLYMACH_POLYGON_RPC_URLS`: optional comma-separated Polygon RPC fallback list
- `POLYMACH_WALLET_PRIVATE_KEY`: advanced fallback payment wallet key for `pay()` / `pay_and_start()`
- `POLYMACH_PAYMENT_GAS_LIMIT`: optional ERC-20 transfer gas override
- `POLYMACH_PAYMENT_GAS_PRICE_WEI`: optional gas price override
- `POLYMACH_PAYMENT_REPLACEMENT_ATTEMPTS`: optional number of same-nonce replacement attempts for pending payments
- `POLYMACH_PAYMENT_REPLACEMENT_GAS_BUMP_PERCENT`: optional gas-price bump percent for replacement attempts

Default Polygon RPC fallback order:

```text
https://polygon.publicnode.com
https://1rpc.io/matic
https://polygon-rpc.com
```

### Live Trading

- `POLYMACH_LIVE_ENABLED`
- `POLYMACH_LIVE_ACK`
- `POLYMACH_POLYMARKET_PRIVATE_KEY`
- `POLYMACH_POLYMARKET_SIGNATURE_TYPE`
- `POLYMACH_POLYMARKET_FUNDER`
- `POLYMACH_POLYMARKET_API_KEY`
- `POLYMACH_POLYMARKET_API_SECRET`
- `POLYMACH_POLYMARKET_API_PASSPHRASE`
- `POLYMACH_POLYMARKET_HOST`
- `POLYMACH_POLYMARKET_CHAIN_ID`
- `POLYMACH_POLYMARKET_GAMMA_API_URL`

## Security

- The Rust engine source is not included in this repo.
- Prefer a dedicated low-balance payment wallet for automated subscription payments.
- Keep private keys out of shell history, chat logs, and code.

## License And Legal

- MIT license: [`LICENSE`](LICENSE)
- legal notice and responsibility disclaimer: [`LEGAL.md`](LEGAL.md)
