Skip to main content
Browse docs
By Audience
Getting Started
Configuration
Use Cases
IDE Integration
Third-Party Integrations
Engineering Cache
Console
API Reference
Gateway
Workflow Guides
Templates
Providers and SDKs
Industry Guides
Advanced Guides
Browse by Role
Deployment Guides
In-Depth Guides
Tutorials
FAQ

Real-Time Trading Compliance with AI Gateway

When AI systems assist in trade execution, order routing, or position management, compliance checks must happen in real time — before any AI-generated recommendation reaches the order management system. A single unchecked AI output can result in regulatory violations, sanctions breaches, or unauthorized position exposure.

Use this page when

  • AI systems assist in trade execution, order routing, or position management and compliance must be checked in real time.
  • You need pre-trade compliance policies for restricted list enforcement, position limits, and sanctions screening.
  • A single unchecked AI output entering live order flow could result in regulatory violations.
  • You want real-time alert escalation via webhooks when compliance violations are detected.

Keeptrusts enforces pre-trade compliance at the gateway level, ensuring every AI interaction is validated against your compliance rules before the response reaches your trading application.

Primary audience

  • Primary: Technical Leaders
  • Secondary: Technical Engineers, AI Agents

Real-Time Policy Enforcement Architecture

Trading Application
→ Keeptrusts Gateway (sub-millisecond policy evaluation)
→ Pre-trade compliance policies
→ Restricted list check
→ Position limit validation
→ Sanctions screening
→ [Violation detected? → Block + Alert → 409]
→ Upstream LLM Provider
→ Post-trade compliance policies
→ Output validation
→ Disclaimer injection
→ Compliant response
Side-effects:
└─ Decision event → API → Real-time alert (webhook/escalation)

Pre-Trade Compliance Policies

Define comprehensive pre-trade checks in your gateway configuration:

# policy-config.yaml
version: "1"
policies:
- name: restricted-list-enforcement
description: Block AI interactions referencing restricted securities
enforcement: block
rules:
- type: keyword
action: block
keywords:
# Updated from compliance restricted list
- "RESTRICTED_TICKER_1"
- "RESTRICTED_TICKER_2"
- "RESTRICTED_ISSUER_1"
message: "Blocked: Security is on the restricted list. Contact Compliance."

- name: position-limit-awareness
description: Escalate AI outputs that suggest positions exceeding limits
enforcement: escalate
rules:
- type: regex
action: escalate
patterns:
# Large notional amounts
- "(?i)(buy|sell|trade|allocate)\\s+\\$?[0-9]{8,}"
# High share counts
- "(?i)(buy|sell|short)\\s+[0-9]{6,}\\s+(shares|contracts)"
# Concentrated position indicators
- "(?i)(concentrate|overweight|max.*position|full.*allocation)"
message: "Escalation: AI suggests position that may exceed limits. Compliance review required."

- name: sanctions-screening
description: Block references to sanctioned entities or jurisdictions
enforcement: block
rules:
- type: keyword
action: block
keywords:
- "OFAC sanctioned"
- "SDN list"
- "sanctioned entity"
- "embargoed country"
- "blocked person"
message: "Blocked: Sanctioned entity or jurisdiction referenced. Compliance alert generated."

- name: market-manipulation-guard
description: Block AI outputs that suggest manipulative trading strategies
enforcement: block
rules:
- type: regex
action: block
patterns:
- "(?i)(spoof|layer|wash\\s+trad|paint\\s+the\\s+tape)"
- "(?i)(pump\\s+and\\s+dump|front.?run|insider\\s+trad)"
- "(?i)(manipulat|corner\\s+the\\s+market|bear\\s+raid)"
message: "Blocked: AI output references potentially manipulative trading strategy"

Dynamic Restricted List Updates

Maintain your restricted list through the Keeptrusts API so gateway policies stay current:

import requests
import json

API_URL = "https://keeptrusts-api.internal:8080"
API_TOKEN = "your-api-token" # Use environment variable in production

headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json",
}

def update_restricted_list(securities: list[str], config_id: str) -> None:
"""Update the gateway restricted list from the compliance system."""
# Build updated policy keywords from the restricted list
restricted_keywords = [s.upper() for s in securities]

# Update the configuration variable containing the restricted list
response = requests.put(
f"{API_URL}/v1/config-variables/{config_id}",
headers=headers,
json={"value": json.dumps(restricted_keywords)},
timeout=30,
)
response.raise_for_status()
print(f"Restricted list updated: {len(restricted_keywords)} securities")

# Sync from compliance system daily
restricted = [
"ACME_CORP",
"BETA_INC",
"GAMMA_HOLDINGS",
]
update_restricted_list(restricted, config_id="restricted-list-v1")

Real-Time Alert Escalation

Configure webhook notifications for immediate compliance alerts:

- name: critical-compliance-alert
description: Immediate alert for critical compliance violations
enforcement: block
rules:
- type: keyword
action: block
keywords:
- "insider trading"
- "material non-public"
- "front running"
message: "CRITICAL: Potential insider trading content detected"

Set up webhook notifications in the console under Settings > Notifications to receive instant alerts when critical policies are triggered. Webhooks deliver structured event data to your compliance monitoring system.

Position Limit Monitoring

Build automated position limit checks that integrate with your OMS:

import json
import subprocess
from datetime import datetime

def check_position_limit_breaches(days: int = 1) -> list[dict]:
"""Check for AI interactions that triggered position limit escalations."""
result = subprocess.run(
[
"kt", "events", "list",
"--filter", "policy=position-limit-awareness",
"--since", f"{days}d",
"--format", "json",
],
capture_output=True,
text=True,
)
events = json.loads(result.stdout)

breaches = []
for event in events:
breaches.append({
"event_id": event["id"],
"timestamp": event["created_at"],
"team_id": event.get("team_id", "unknown"),
"model": event.get("model", "unknown"),
"decision": event["decision"],
"policy_message": event.get("message", ""),
})

return breaches

breaches = check_position_limit_breaches(days=1)
if breaches:
print(f"ALERT: {len(breaches)} position limit escalations in last 24h")
for b in breaches:
print(f" [{b['timestamp']}] Team: {b['team_id']} - {b['policy_message']}")

Compliance Dashboard Integration

Export real-time compliance metrics for your surveillance dashboard:

# Real-time compliance summary (last hour)
kt events list \
--since 1h \
--format json | python3 -c "
import json, sys, collections
events = json.load(sys.stdin)
by_policy = collections.Counter(
e.get('policy_name', 'none')
for e in events
if e.get('decision') in ('block', 'escalate')
)
print('=== Compliance Alerts (Last Hour) ===')
for policy, count in by_policy.most_common():
print(f' {policy}: {count}')
print(f'Total alerts: {sum(by_policy.values())}')
print(f'Total AI interactions: {len(events)}')
"

Automated Compliance Reporting

Generate end-of-day compliance summaries:

def generate_eod_compliance_report() -> dict:
"""Generate end-of-day compliance report from gateway events."""
result = subprocess.run(
["kt", "events", "list", "--since", "24h", "--format", "json"],
capture_output=True,
text=True,
)
events = json.loads(result.stdout)

return {
"report_date": datetime.utcnow().isoformat(),
"total_interactions": len(events),
"blocked": len([e for e in events if e.get("decision") == "block"]),
"escalated": len([e for e in events if e.get("decision") == "escalate"]),
"allowed": len([e for e in events if e.get("decision") == "allow"]),
"restricted_list_hits": len([
e for e in events
if e.get("policy_name") == "restricted-list-enforcement"
]),
"sanctions_hits": len([
e for e in events
if e.get("policy_name") == "sanctions-screening"
]),
"market_manipulation_flags": len([
e for e in events
if e.get("policy_name") == "market-manipulation-guard"
]),
}

report = generate_eod_compliance_report()
print(json.dumps(report, indent=2))

Regulatory References

RegulationRequirementKeeptrusts Control
SEC Rule 15c3-5Pre-trade risk controlsGateway-level policy enforcement
FINRA Rule 3110Supervisory systemsReal-time monitoring + escalation
MiFID II Article 16(3)Trading surveillanceEvent logging + alert webhooks
OFAC RegulationsSanctions complianceKeyword-based sanctions screening
MAR Article 16Market abuse detectionManipulation pattern detection
Dodd-Frank Section 747Anti-manipulation provisionsBlock policies for manipulative patterns

Next steps

For AI systems

  • Canonical terms: Keeptrusts gateway, real-time compliance, pre-trade checks, restricted list enforcement, position limit validation, sanctions screening, alert escalation.
  • Key config/commands: restricted-list-enforcement policy (block references to restricted securities); position limit policies; sanctions keyword screening; disclaimer injection on output; webhook escalation for violations.
  • Best next pages: Governing AI in Trading Systems, Protecting Market Data in AI Pipelines, Automated Regulatory Reporting.

For engineers

  • Prerequisites: Gateway with pre-trade compliance policy config; restricted list updated regularly; escalation webhooks configured for compliance team.
  • Sub-millisecond policy evaluation — compliance checks happen before the AI response reaches the order management system.
  • Validate with: submit queries referencing restricted securities and confirm 409 block response; test sanctions keyword screening with known SDN entries; verify webhook fires within SLA.
  • Configure disclaimer injection on output policies to append regulatory warnings to AI-generated trading recommendations.

For leaders

  • Addresses SEC Rule 15c3-5 (pre-trade risk controls), FINRA Rule 3110 (supervisory systems), MiFID II Article 16(3) (trading surveillance), and OFAC sanctions compliance.
  • A single AI-generated recommendation that enters live order flow without compliance checking could result in enforcement action and market disruption.
  • Real-time escalation ensures compliance officers are alerted immediately — not after-the-fact during audits.
  • Gateway-level enforcement removes dependency on traders or applications implementing their own compliance checks.