Python SDK for reTrade, a pre-trade check for AI trading agents: every order gets ALLOW, CUT or BLOCK with a signed receipt
pip install retrade==0.1.1 Copy PIP instructions
reTrade is a pre-trade check for AI trading agents. Before your agent's order goes to your broker, the SDK sends it to reTrade, which checks it against the rules your tenant's admins set, and answers at once:
Every answer is signed by reTrade and chained into your tenant's log. The SDK checks each signature before it acts, places orders through your own broker connection (reTrade never connects to your broker), and keeps the signed records in a local file.
Status: in development. This is version 0.1.1 of the SDK, built to the wire spec retrade-arith/2.0-draft, which may still change: pin the version you test with. The SDK's default address is the hosted service, https://api.retrade.app; to use a reTrade server you run instead, pass base_url (how to run one).
pip install retrade Python 3.12 or later. The one dependency is cryptography. The package also installs the retrade command.
Make the executor key on the machine that will run your agent:
retrade keygen executor.pem It writes the private key (file mode 0600) and prints its public half. Send only the public half to your tenant's admin. The admin registers it with retrade-admin keys add-executor --mode enforce and sends you back the key_id that command prints: that is your bot key id. The mode in the id (enforce, shadow or test) is the mode of every order the key asks about. Keep executor.pem secret: anyone holding it can ask for decisions as your agent.
import retrade rt = retrade.Client( "exk_enforce_01M...", # your bot key id "executor.pem", # your executor key file root_key=" ", base_url="http://127.0.0.1:8080", ) The server's address comes from, in this order: the base_url argument, then the RETRADE_BASE_URL environment variable, then retrade.DEFAULT_BASE_URL (https://api.retrade.app, the hosted service). So you can leave base_url out and run with RETRADE_BASE_URL=http://127.0.0.1:8080. Plain http is allowed only for a loopback address (127.0.0.1, localhost, ::1). The older keyword server= still works.
The root key is pinned: the SDK never fetches it. On start-up it fetches reTrade's list of signing keys and checks the list against the root key. The claim kit (below) goes in state_dir, retrade-state by default.
The SDK reads the account and places orders through four functions you write against your broker's own API:
from datetime import UTC, datetime from decimal import Decimal def read_account(instrument, adjustments_since): """Read the account from your broker now, and a quote for `instrument` when it is given.""" now = datetime.now(UTC) snapshot = retrade.Snapshot( as_of=now, cash={"USD": Decimal("38380.90")}, # from your broker settled_cash={"USD": Decimal("38380.90")}, # from your broker positions=(retrade.Position("XNAS:AAPL", 81, Decimal("187.10")),), open_orders=(), ) if instrument is None: return snapshot, None return snapshot, retrade.Quote(instrument, Decimal("187.10"), Decimal("187.08"), Decimal("187.12"), now) broker = retrade.GenericAdapter( snapshot=read_account, submit=place_order, # (retrade.ApprovedOrder, tag) -> the broker's order id find=find_order, # (tag, retrade.ApprovedOrder, since) -> the broker's order id, or None cancel=cancel_order, # (broker order id) -> None g_seconds=60, # must equal the account's g_seconds at reTrade converts_cash=True, # must equal the account's converts_cash at reTrade ) submit places exactly the ApprovedOrder it is given, with tag in the broker's client-order-id field. It raises retrade.BrokerRejected only when the broker definitely refused the order, and lets any other error through when the outcome is unknown. The SDK never retries a submit.
from retrade import OrderType, Side, Tif order = retrade.Order("XNAS:AAPL", Side.BUY, 40, OrderType.LIMIT, Tif.DAY, limit_price=Decimal("187.25")) result = rt.place(order, account="A1", agent="agt_momentum", via=broker) account is the account's ref in your tenant's account register. agent names the agent sending the order. Instruments are : , such as XNAS:AAPL. Plain strings ("buy", "limit", "day") and lists work too; the enums and tuples are what a type checker accepts. The package ships its type hints (py.typed).
if result.outcome == "ALLOW": print("placed as sent:", result.broker_order_id) elif result.outcome == "CUT": print(f"placed {result.quantity} of {result.requested_quantity}:", result.deciding) elif result.fits: # BLOCK at an approval line or an agent conflict, and a smaller order would pass. The resend is a new # decision and counts toward the agent's per-minute limit, so resend once, don't loop. smaller = retrade.Order("XNAS:AAPL", Side.BUY, result.fits, OrderType.LIMIT, Tif.DAY, limit_price=Decimal("187.25")) result = rt.place(smaller, account="A1", agent="agt_momentum", via=broker) else: # BLOCK, nothing placed: reTrade's rule, or the SDK's own reason when it had no verified answer. print("blocked:", result.deciding or result.reason) Check result.placement as well: placed, not_placed (the broker refused it, or it was never sent), or unknown (the broker call's outcome isn't known yet; don't place the order again). result.deciding is reTrade's deciding rule, for example {"code": "approval_line", "reason": "per_order"} or {"code": "order_size_cap"}. result.fits is set only on a BLOCK at an approval line or an agent conflict. It is 0 when no size would pass. result.local is True when the SDK decided without a verified answer from reTrade, with result.reason saying why: for example unreachable (no answer within 2.5 s) or unverified (the answer failed a check). In enforce and test mode the order is then not placed. Verify receipts The SDK checks every signed answer before it uses it:
An answer that fails any check is never placed (result.reason == "unverified"). Everything is kept in retrade-state/claim-kit.sqlite3: the request bytes, the signed decision, the policy it was decided under, your report and reTrade's receipt. To read the evidence for one decision:
if result.decision_id is not None: # None only when the SDK decided on its own evidence = rt.claim_kit(result.decision_id) # {"format": "retrade-claim-kit/1", "decision_id": ..., "request": ..., "decision": ..., "policy": ..., # "report": ..., "receipt": ..., "heads": [...]} or, on the command line, retrade claim-kit --state-dir retrade-state. decision and receipt are compact JWS documents (Ed25519). Anyone with the root public key can check them again against GET /v1/keys, as API.md sections 3 and 4 describe. Keep the file for at least 90 days. The TypeScript SDK reads and writes the same format.
To read your tenant's log for this key's mode, each record verified and chained to the one before it:
records = rt.log() # the whole log, from record 1: a list of retrade.LogRecord (seq, kind, hash, token, payload) first20 = rt.log(from_seq=1, to_seq=20) # records 1 to 20 reTrade sends the log a page at a time (at most 1,000 records and 512 KiB a page), and log() asks for one page after another until it reaches to_seq or the end of the log. Each page has its own 2.5 s deadline. The records it returns are held in memory, so read a very long log in ranges.
reTrade offers no guarantee and pays no losses. The signed records are evidence of what was asked, what reTrade answered and what was placed, nothing more.
The SDK's own reasons: unreachable (no answer in 2.5 s), unverified (the answer failed a check, including one whose order fields differ from what was sent), exits-only: (exits-only refused the sell), exit (exits-only placed it), shadow-unreachable and shadow-unverified, expired and stopped (an approved order withdrawn before the broker call), already-used, broker-rejected and broker-outcome-unknown.
uv sync uv run python -m pytest -q uv run ruff check . uv run mypy The server end-to-end test (tests/test_server_e2e.py) is skipped unless a server is running; the Rust test server/tests/sdk_e2e.rs starts one and runs it.
trading pre-trade risk ai-agents orders broker ed25519 receipts
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
None of the files in this release were uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.




