Metadata-Version: 2.4
Name: gamegains-sdk
Version: 0.3.0
Summary: Official Python SDK for the GameGains perpetual-futures trading API.
Author: GameGains
License: MIT
Project-URL: homepage, https://gamegains.gg
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: eth-account>=0.13.0
Requires-Dist: httpcore>=1.0.9
Requires-Dist: httpx>=0.28.1
Requires-Dist: pydantic<2.13,>=2.11.2
Requires-Dist: websockets>=12
Dynamic: license-file

# GameGains Python SDK

[![PyPI version](https://img.shields.io/pypi/v/gamegains-sdk.svg)](https://pypi.org/project/gamegains-sdk/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Official Python SDK for the [GameGains](https://gamegains.gg) perpetual-futures trading API. HMAC + EIP-712 signing are built in — you provide keys, the SDK signs every request.

The live beta runs on Arbitrum Sepolia (chainId 421614). Read `chain_id` and `settlement_address` from `GET /api/v1/exchange-info` at startup rather than hard-coding them.

```bash
pip install gamegains-sdk
```

## Quickstart

### Public (unauthenticated) data

```python
from gamegains_sdk import GameGains

gg = GameGains(server_url="https://api.gamegains.gg")
info = gg.markets.get_exchange_info()          # chain_id, settlement_address, symbols
price = gg.market_data.get_oracle_price(market="AK47-REDLINE-FT")
print(price.mark_price, price.is_stale)
```

### Authenticated (auto-signed) requests

Every authenticated request is signed with your API **secret** using HMAC-SHA256. Provide the key on the client and the secret via `set_api_secret` (or the `GG_API_SECRET` env var); the SDK's request hook does the rest.

```python
from gamegains_sdk import GameGains, set_api_secret

gg = GameGains(server_url="https://api.gamegains.gg", gg_apikey="gg_pk_...")
set_api_secret("gg_sk_...")                    # shown once at key creation

acct = gg.account.get_account()                # signed automatically
print(acct.collateral.total)
```

`set_api_secret` is process-wide. When one process holds several keys (a maker and a taker, sub-accounts), give each client its own secret instead — each then signs with its own key, also concurrently:

```python
maker = GameGains(server_url=..., gg_apikey=maker_key, api_secret=maker_secret)
taker = GameGains(server_url=..., gg_apikey=taker_key, api_secret=taker_secret)
```

## Signing helpers (EIP-712 + cancel intents)

Orders, API keys, and cancels are authorized by your **wallet** signature. The SDK ships the exact signers (byte-identical to the gateway) so a self-custody / linked wallet can sign locally:

```python
from gamegains_sdk import (
    sign_order_intent, sign_api_key_create, to_engine8,
    sign_cancel_intent, sign_cancel_all_intent, sign_amend_intent,
)

info = gg.markets.get_exchange_info()
chain_id, settlement = int(info.chain_id), info.settlement_address

# Place an order. A pre-signed price is forwarded verbatim, and the engine rejects an
# off-grid one (PRICE_NOT_ON_TICK): quantize to the symbol's tick BEFORE signing.
tick = int(next(s for s in info.symbols if s.symbol == "AK47-REDLINE-FT").tick_size_8dp)
price = (to_engine8(30.714) // tick) * tick / 1e8          # 30.71 on a $0.01 tick
sig = sign_order_intent(
    private_key, chain_id, settlement,
    trader=address, symbol="AK47-REDLINE-FT", side="long", order_type="limit",
    price=price, size_usd=100, leverage=2, nonce=nonce, expiry=expiry,
)
# ...pass sig as the order body's `signature` field to gg.orders.create_order(...)

# Close a long: a reduce-only order on the OPPOSITE side, sized to the position.
# price must be > 0 on every order (price=0 is rejected). For market and reduce-only
# orders it is a hard worst-price limit: a short/sell fills at or above it, a long/buy
# at or below it.
sig = sign_order_intent(..., side="short", order_type="market",
                        price=worst_price, size_usd=position_notional, reduce_only=True)

# Cancel a resting order (linked wallets must pre-sign — see below)
c = sign_cancel_intent(private_key, chain_id=chain_id, order_id=order_id)  # -> {"signature", "timestamp"}
gg.orders.cancel_order(order_id=order_id, **c)
```

Resting prices (limit, post-only, stop-limit, take-profit-limit) and trigger prices must sit on the market's tick grid: the engine rejects an off-grid signed price rather than rounding it. Quantize to `symbols[].tick_size_8dp` from `get_exchange_info()` before signing. The tick is an 8-decimal integer string, so a price is on the grid when `to_engine8(price) % int(sym.tick_size_8dp) == 0` (`to_engine8` is exported by the SDK).

`chain_id` and `settlement_address` go into the signed bytes, so every signer checks them and raises `ValueError` naming the signer instead of returning a signature the engine rejects. `chain_id` may be an int, the float `info.chain_id` parses into, or a string of decimal digits; all three sign identical bytes. Anything else is refused, including `Decimal` and strings with whitespace or a decimal point: pass `int(value)`. `settlement_address` must be a `0x`-prefixed 40-hex-digit string, not bytes. The TypeScript SDK applies the same rule, except that it refuses a chain id above 2^53 - 1.

The cancel-family signers (`sign_cancel_intent`, `sign_cancel_all_intent`, `sign_cancel_batch_intent`, `sign_amend_intent`, `sign_dead_man_switch_intent`) produce a `personal_sign` over the raw keccak256 of a `GG:<chainId>:`-prefixed payload, so pass the same `chain_id` you sign orders with. Send the returned `{signature, timestamp}` with the request; the timestamp is unix seconds (milliseconds for cancel-batch) and is accepted within ±120s, once. A **linked** wallet (your own key) must supply it, or the request is rejected with `SIGNATURE_REQUIRED`; only **custodial** wallets, whose key the gateway holds, may omit it. Cancel-batch reports that rejection differently: `cancel_order_batch` returns HTTP 200 with `success=False` and `error_code` `SIGNATURE_REQUIRED` on every entry of `results`, so check every result, not the status code.

The engine burns every signed cancel-family payload once. Cancel-all, cancel, amend and dead-man-switch payloads carry a unix-**seconds** timestamp, so two identical ones signed in the same second (for example two `sign_cancel_all_intent(symbol=m)` calls) are the same bytes and the second is rejected `REPLAY_DETECTED`; space them at least one second apart. Cancel-batch signs milliseconds and is not affected.

## Collateral (vault)

```python
from gamegains_sdk import deposit_to_vault, withdraw_from_vault, usd_to_usdc6

deposit_to_vault(rpc_url, private_key, usdc_address, vault_address, usd_to_usdc6("1000"))
res = withdraw_from_vault(rpc_url, private_key, vault_address, usd_to_usdc6("250"))
# vault without a withdrawal delay: res["withdraw_tx"]; with one: res["request_tx"] and
# res["unlock_time"], then execute_vault_withdraw(rpc_url, private_key, vault_address)
```

The vault only knows the margin of settled positions, not your resting orders or fills the engine has not settled yet. Cancel resting orders (or leave margin for them) and let fills settle before you withdraw. Addresses may be lowercase or checksummed. A mixed-case address whose checksum fails raises `ValueError`, and an address without contract code raises `DepositError`, before anything is sent.

## Full API reference

Every resource method and model carries its reference documentation as docstrings — e.g. `help(gg.orders.create_order)`. Errors raise `gamegains_sdk.errors.*`; retries and timeouts are configurable per call.

Every `market` / `symbol` parameter is typed with one shared literal, `models.TradeableMarket`, with the matching runtime tuple `models.TRADEABLE_MARKETS`, so the tradeable set never differs between endpoints.

## License

MIT.
