Source: [https://trygalore.com/learn/pre-trade-check-python](https://trygalore.com/learn/pre-trade-check-python)

# Pre-trade checks in Python

A failed position lookup is not a zero position. Hold the trade instead.

By Galore. Reviewed 4 December 2026. [Source on GitHub](https://github.com/mehek-builds/galore-examples) · [Watch the 60-second walkthrough](https://trygalore.com/watch/pre-trade-check-python)

## Run in Google Colab

[Open the notebook](https://colab.research.google.com/drive/1W2TIFshiaCURdcc3IWUjuIsaX5f28jnk), then choose **Runtime > Run all** with your own Google account. Checked in Colab on 4 December 2026: fourteen cases, one allowed, thirteen refused, zero broker calls.

## Run it locally

Download [pre_trade_check.py](https://trygalore.com/examples/pre_trade_check.py), read it, and run it with Python 3.10 or later. Standard library only. No keys, no network, no orders.

```
mkdir galore-pretrade && cd galore-pretrade
curl --fail --location --output pre_trade_check.py https://trygalore.com/examples/pre_trade_check.py
# Inspect the downloaded source before running it.
python3 pre_trade_check.py
```

[Expected output](https://trygalore.com/examples/pre-trade-results.json). One case is allowed for simulation; thirteen are refused.

## The mistake to avoid

Do not turn every lookup error into a zero position. An outage, an expired key and a truly empty position mean different things. If you cannot see the account, hold the trade and say why.

```
if evidence is None:
    return "account_state_unknown"
if not 0 <= now - evidence.observed_at <= 30:
    return "account_state_stale"
```

The thirty-second window is an example, not a safe default.

## What it checks

- The rules are verified, unexpired and still on.

- The account, AI and symbol match the rules.

- Account data is present, fresh and matching.

- The session, trade value, position size and buying power fit.

- Numbers are valid decimals.

## Results

Fourteen fixed, hypothetical cases

| Case | Decision |
| --- | --- |
| within_limits | ` allowed_for_simulation ` |
| authority_not_verified | ` authority_unverified ` |
| revoked_permission | ` permission_revoked ` |
| expired_permission | ` permission_expired ` |
| different_account | ` identity_mismatch ` |
| different_agent | ` identity_mismatch ` |
| unapproved_symbol | ` symbol_not_allowed ` |
| missing_position_lookup | ` account_state_unknown ` |
| stale_account_snapshot | ` account_state_stale ` |
| closed_session | ` session_not_allowed ` |
| oversized_order | ` order_limit_exceeded ` |
| oversized_position | ` position_limit_exceeded ` |
| insufficient_buying_power | ` buying_power_exceeded ` |
| nonfinite_quote | ` invalid_numeric_input ` |

## Read the code

Show the Python example

```
"""Galore educational pre-trade check. Python 3.10+, standard library only.

Run: python3 pre_trade_check.py
No broker connection, credentials, network requests or order submission.
This pure example is not the Galore Gate SDK or a production risk engine.
Identity verification, permission signing and durable reservations are external.
"""
from dataclasses import dataclass, replace
from decimal import Decimal, DecimalException
import json


@dataclass(frozen=True)
class Permission:
    account: str
    agent: str
    symbols: tuple[str, ...]
    expires_at: int
    max_order_usd: str
    max_position_usd: str
    revoked: bool = False


@dataclass(frozen=True)
class BuyIntent:
    account: str
    agent: str
    symbol: str
    quantity: str
    limit_price: str


@dataclass(frozen=True)
class AccountEvidence:
    account: str
    observed_at: int
    position_quantity: str
    buying_power_usd: str
    quote: str
    session_allowed: bool


def money(value):
    if not isinstance(value, str) or len(value) > 64:
        raise ValueError("Use a bounded decimal string")
    number = Decimal(value)
    if not number.is_finite() or number < 0:
        raise ValueError("Expected a finite nonnegative decimal")
    return number


def check_buy(permission, intent, evidence, *, now, authority_verified):
    """Call only after a trusted service verifies the customer and agent.

    authority_verified is an upstream trust boundary, not an agent-supplied
    assertion. A True result grants no credential and submits no order.
    Scope: a hypothetical USD-denominated limit buy in a known paper account.
    """
    if authority_verified is not True:
        return "authority_unverified"
    if permission.revoked:
        return "permission_revoked"
    if now >= permission.expires_at:
        return "permission_expired"
    if intent.account != permission.account or intent.agent != permission.agent:
        return "identity_mismatch"
    if intent.symbol not in permission.symbols:
        return "symbol_not_allowed"
    if evidence is None:
        return "account_state_unknown"
    if evidence.account != permission.account:
        return "account_state_mismatch"
    if not 0 <= now - evidence.observed_at <= 30:
        return "account_state_stale"
    if evidence.session_allowed is not True:
        return "session_not_allowed"
    try:
        quantity, limit_price = money(intent.quantity), money(intent.limit_price)
        position, buying_power = money(evidence.position_quantity), money(evidence.buying_power_usd)
        quote = money(evidence.quote)
        max_order, max_position = money(permission.max_order_usd), money(permission.max_position_usd)
        if quantity == 0 or limit_price == 0 or quote == 0:
            return "invalid_numeric_input"
        order_cost = quantity * limit_price
        # Conservative hypothetical marked exposure, not a broker margin model.
        position_value = (position + quantity) * max(quote, limit_price)
        if order_cost > max_order:
            return "order_limit_exceeded"
        if position_value > max_position:
            return "position_limit_exceeded"
        if order_cost > buying_power:
            return "buying_power_exceeded"
    except (DecimalException, TypeError, ValueError):
        return "invalid_numeric_input"
    return "allowed_for_simulation"


def scenarios():
    now = 1_800_000_000
    permission = Permission("paper-example", "example-agent", ("EXAMPLE",), now + 60, "500", "2000")
    intent = BuyIntent("paper-example", "example-agent", "EXAMPLE", "2", "100")
    state = AccountEvidence("paper-example", now, "3", "1000", "100", True)
    cases = [
        ("within_limits", permission, intent, state, True),
        ("authority_not_verified", permission, intent, state, False),
        ("revoked_permission", replace(permission, revoked=True), intent, state, True),
        ("expired_permission", replace(permission, expires_at=now), intent, state, True),
        ("different_account", permission, replace(intent, account="another-account"), state, True),
        ("different_agent", permission, replace(intent, agent="another-agent"), state, True),
        ("unapproved_symbol", permission, replace(intent, symbol="OTHER"), state, True),
        ("missing_position_lookup", permission, intent, None, True),
        ("stale_account_snapshot", permission, intent, replace(state, observed_at=now - 31), True),
        ("closed_session", permission, intent, replace(state, session_allowed=False), True),
        ("oversized_order", permission, replace(intent, quantity="6"), state, True),
        ("oversized_position", permission, intent, replace(state, position_quantity="20"), True),
        ("insufficient_buying_power", permission, intent, replace(state, buying_power_usd="100"), True),
        ("nonfinite_quote", permission, intent, replace(state, quote="NaN"), True),
    ]
    return [{"scenario": name, "decision": check_buy(p, i, e, now=now, authority_verified=verified)}
            for name, p, i, e, verified in cases]


if __name__ == "__main__":
    print(json.dumps({"mode": "local_simulation_only", "broker_requests": 0, "results": scenarios()}, indent=2))

```

## What it does not do

It models a USD limit buy with practice money and trusts its inputs. An AI must never set ` authority_verified ` itself. There is no login, signature, brokerage connection, sell protection, shorting, margin or tamper-evident record. A real integration also needs stable order IDs, reservations and reconciliation. If a send times out, keep the outcome unknown instead of placing another order. Passing this check is not a fill.

[Next: a retry journal for timeouts](https://trygalore.com/learn/prevent-duplicate-trading-orders).

## Where Galore fits

Galore runs these checks for real, against rules the person approved. This download is teaching code, not a Galore SDK. [Run the Galore runtime locally](https://trygalore.com/developers/gate-evaluation).

[Developer docs](https://trygalore.com/developers) · [Compare approaches](https://trygalore.com/compare/pre-trade-tools) · [Contact us](https://trygalore.com/contact)

Reviewed 4 December 2026
