pagina iniziale

Per iniziare

SDK per Python e Rust

SDK ufficiali di Seeryx per Python e Rust: dati di mercato, Sign-In With Solana, ordini firmati, depositi e prelievi verificati prima della firma, flussi live.

Panoramica

Gli SDK ufficiali racchiudono l’API di queste pagine per Python e Rust, con gli stessi concetti e gli stessi nomi in entrambi i linguaggi. Sono open source con licenza MIT: github.com/Seeryx/seeryx-python e github.com/Seeryx/seeryx-rust.

  • Dati di mercato: mercati, round in corso e passati, libri ordini, operazioni, volume, commissioni, statistiche, classifica, profili e mercati sugli eventi, senza account.
  • Sign-In With Solana con la coppia di chiavi del tuo wallet; quando il token scade, l’SDK accede di nuovo da solo.
  • Trading: una sessione di trading aperta con una sola firma del wallet, poi ordini limite, a mercato e post only, lotti fino a 15 ordini, annullamenti, divisioni e unioni, tutto firmato sul tuo computer.
  • Fondi: depositi dal tuo wallet, prelievi sul tuo wallet e prelievi differiti; ogni transazione viene controllata prima della firma.
  • In tempo reale: flussi WebSocket di un round e del tuo conto, che si riconnettono da soli.
  • Funzioni di supporto: la griglia dei prezzi, le commissioni, gli slug e gli orari dei round.

Installa

Python 3.9 o successivo (un Client bloccante e un AsyncClient asyncio con gli stessi metodi) oppure Rust 1.88 o successivo (asincrono, su tokio). Entrambi si installano da GitHub:

# Python 3.9 or newer
pip install "git+https://github.com/Seeryx/seeryx-python"

Leggi un mercato

I dati di mercato non richiedono un account. I prezzi sono in centesimi; i livelli del libro ordini sono [prezzo, quote], i migliori per primi.

quickstart.py
"""The live BTC 5-minute round, its order book and its last trades. No account needed.

    python quickstart.py
"""
from seeryx import Client

with Client() as client:
    rnd = client.current_round("BTC", "5m")
    book = client.order_book(rnd["slug"], "up")  # levels are [cents, shares], best first
    trades = client.trades(rnd["slug"])

    bid = book["bids"][0][0] if book["bids"] else None
    ask = book["asks"][0][0] if book["asks"] else None
    print(rnd["slug"], "opened at", rnd["open"], "ends at", rnd["end"])
    print("Up bid", bid, "ask", ask, "chance of Up", f"{(bid + ask) / 2}%" if bid and ask else "no quotes yet")
    print("last trade", trades[0] if trades else "none yet")
    print("taker fee", client.fees()["rateBps"] / 100, "% of p x (1 - p) per share")

Accedi

Carica il tuo wallet da un file di coppia di chiavi della Solana CLI o da una chiave segreta in base58; non lascia mai il tuo processo. Prima che il wallet firmi il testo di accesso, l’SDK controlla che indichi questo sito, questo wallet e il nonce appena emesso, poi conserva il token di 7 giorni.

Dove GET /api/funds indica onChainTrading, una sola firma del wallet apre una sessione di trading; la sua chiave, creata sul tuo computer, firma poi ogni ordine. Con un percorso la sessione viene salvata (leggibile solo da te) e riusata all’avvio successivo; senza, resta solo in memoria.

from seeryx import Client, Keypair

client = Client()  # https://seeryx.com
wallet = Keypair.from_file("wallet.json")  # a solana-keygen file; it never leaves this process
client.sign_in(wallet)  # checks the sign-in text, signs it, keeps the 7-day token
if client.funds().get("onChainTrading"):
    # one wallet signature; the session key then signs every order. Saved with mode 0600 and reused next time
    session = client.open_session(wallet, path="session.json")
    print("session key", session.address, "until", session.expires_at)

Inserisci un ordine

I prezzi sono in centesimi (in decimi dove il mercato li consente), le dimensioni in quote, gli importi in USDC. L’SDK sceglie la forma firmata (PMO2, PMO3 o PMO4), l’id dell’ordine e la scadenza; un ordine a mercato richiede cap, il prezzo peggiore che accetti.

limit_order.py
"""Sign in, rest a small post-only buy below the market, list it, then cancel it.

    SEERYX_WALLET=~/.config/solana/id.json python limit_order.py
"""
import os

from seeryx import Client, Keypair

wallet = Keypair.from_file(os.path.expanduser(os.environ.get("SEERYX_WALLET", "wallet.json")))

with Client() as client:
    client.sign_in(wallet)
    if client.funds().get("onChainTrading"):
        # one wallet signature opens a trading session; its key then signs every order. Saved (mode 0600) so the
        # next run reuses it; leave out `path` to keep the key in memory only.
        client.open_session(wallet, path="session.json")

    rnd = client.current_round("BTC", "5m")
    book = client.order_book(rnd["slug"], "up")
    bid = book["bids"][0][0] if book["bids"] else 10
    limit = max(1, int(bid) - 5)  # 5c under the best bid: it rests in the book
    placed = client.buy(rnd["slug"], "up", shares=5, limit=limit, post_only=True)  # post_only: never trades at once
    print("resting order", placed["order"], "at", limit, "c")

    print("open orders", client.open_orders())
    if placed["order"]:
        print(client.cancel_order(placed["order"]))
market_buy.py
"""Spend up to $5 on Up now, paying at most 2c over the best ask. What the book cannot fill is dropped.

    SEERYX_WALLET=~/.config/solana/id.json python market_buy.py
"""
import os

from seeryx import Client, Keypair

wallet = Keypair.from_file(os.path.expanduser(os.environ.get("SEERYX_WALLET", "wallet.json")))

with Client() as client:
    client.sign_in(wallet)
    if client.funds().get("onChainTrading"):
        client.open_session(wallet, path="session.json")
    slug = client.current_round("BTC", "5m")["slug"]
    cap = client.market_cap(slug, "up", "buy", slippage=2)  # the worst price you accept, on the price grid
    result = client.market_buy(slug, "up", amount=5, cap=cap)
    print(result["status"], "filled", result["filled"], "shares for", result["spent"], "USDC, average", result.get("avgPrice"))

Aggiornamenti in tempo reale

Un flusso segue un round o un mercato sugli eventi (entrambi i libri ordini, operazioni, volume) e, dopo l’accesso, il tuo conto. Si riconnette con un ritardo crescente e si iscrive di nuovo; quando un round finisce, segui il successivo sulla stessa connessione.

stream.py
"""Live books and trades of the BTC 5-minute rounds, and your account, over the WebSocket. Reconnects by itself.

    python stream.py                                           # market data only
    SEERYX_WALLET=~/.config/solana/id.json python stream.py    # and your account
"""
import asyncio
import os
import time

from seeryx import AsyncClient, Keypair


async def main() -> None:
    async with AsyncClient() as client:
        path = os.environ.get("SEERYX_WALLET")
        if path:
            await client.sign_in(Keypair.from_file(os.path.expanduser(path)))
        rnd = await client.current_round("BTC", "5m")
        async with client.stream(rnd["slug"], account=bool(path)) as stream:
            while True:
                # a message comes only when something changed: wait at most until the round ends
                message = await stream.next(timeout=max(1.0, rnd["end"] - time.time()))
                if message is None or time.time() >= rnd["end"]:
                    rnd = await client.current_round("BTC", "5m")  # follow the next round, same connection
                    await stream.watch_round(rnd["slug"])
                    continue
                if message["type"] == "round":
                    up = message["up"]
                    print(message["slug"], "bid", up["bids"][:1], "ask", up["asks"][:1], "volume", message["volume"])
                elif message["type"] == "account":
                    print("cash", message["balance"]["available"], "open orders", len(message["orders"]))
                else:
                    print("error", message["error"])


asyncio.run(main())

Deposita e preleva

La piattaforma prepara ogni transazione e ne paga la commissione di rete, quindi al tuo wallet non serve SOL. L’SDK la confronta esattamente con quanto hai chiesto e non firma nient’altro. Un prelievo è firmato dalla chiave di sessione dove sessionWithdraw è attivo (almeno 1 USDC, solo sul tuo wallet), altrimenti dal tuo wallet.

withdraw.py
"""Deposit USDC from your wallet, then withdraw some of it to the same wallet. The exchange pays every network fee:
the wallet needs no SOL. Every transaction is inspected before it is signed.

    SEERYX_WALLET=~/.config/solana/id.json python withdraw.py
"""
import os

from seeryx import Client, Keypair

wallet = Keypair.from_file(os.path.expanduser(os.environ.get("SEERYX_WALLET", "wallet.json")))

with Client(before_sign=lambda review: print("signing:", review.headline) or True) as client:
    client.sign_in(wallet)
    print("wallet", client.wallet_funds())  # USDC in the wallet; "account" is None until the first deposit

    print("deposit", client.deposit(wallet, 10))  # the first deposit is at least 1 USDC
    print("balance", client.balance())

    # signed by the trading session key when one is open and the server allows it, else by the wallet;
    # max_fee refuses a withdrawal fee above 1 USDC
    if client.funds().get("onChainTrading"):
        client.open_session(wallet, path="session.json")
    print("withdrawal", client.withdraw(4, wallet=wallet, max_fee=1))
    print("balance", client.balance())

Errori e nuovi tentativi

Un rifiuto arriva come errore con lo stato, il testo del server e il suo code; i codici dell’elenco degli errori hanno tipi propri. Le risposte 429 e 503 vengono ritentate come indica Retry-After, e le scritture mantengono la loro Idempotency-Key a ogni nuovo tentativo, così nulla viene inserito due volte.

from seeryx import ApiError, BelowMinimum, WouldTake

try:
    client.buy(slug, "up", shares=5, limit=60, post_only=True)
except WouldTake:
    print("it would trade at once: post only refused it")
except BelowMinimum as e:
    print("the smallest order is", e.minimum, "shares")
except ApiError as e:
    print(e.status, e.code, e.message)  # 429 and 503 were already retried as Retry-After said

Chiavi e controlli

  • La chiave del tuo wallet e la chiave di sessione non lasciano mai il tuo processo: vengono inviate solo chiavi pubbliche e firme.
  • Ogni transazione preparata viene decodificata e deve essere l’istruzione propria del programma Seeryx con i tuoi conti e i tuoi importi: un’autorizzazione di spesa, un trasferimento, un altro firmatario o un altro programma viene rifiutato.
  • Su seeryx.com il programma, il mint di USDC e il cluster Solana sono fissati, qualunque cosa riporti il server.
  • Nulla che contenga un segreto viene stampato o registrato nei log, e un file di sessione salvato è leggibile solo dal suo proprietario.

Esempi

Entrambi i linguaggi hanno gli stessi programmi nelle cartelle examples:

EsempioCosa fa
quickstartIl round BTC di 5 minuti in corso, il suo libro ordini e le ultime operazioni, senza account
limit_orderAccedere, mettere in attesa un acquisto post only sotto il mercato, elencarlo e annullarlo
market_buySpendere subito fino a 5 $, pagando al massimo 2¢ sopra la migliore offerta in vendita
streamLibri ordini, operazioni e il tuo conto in tempo reale tramite il WebSocket
market_makerUn piccolo ciclo di quotazione su entrambi i lati con ordini post only e unioni
withdrawDepositare dal tuo wallet e prelevare di nuovo verso di esso

Codice sorgente, tutti i metodi, i test e il registro delle modifiche: github.com/Seeryx/seeryx-python e github.com/Seeryx/seeryx-rust.