← Financial Trader Cloud Trader Hub · Backtest

Vertex Macro | Financial Trader Cloud · AMZN Backtest Desk · May 2026

Build Modern Volatility Trading & Lawful Thailand Recovery Planning Agents: A Memory-Driven Strands Multi-Agent Risk Protection System

Series: Backtest

Note: 11

Article
Kiro workshop
01 Build with Kiro: Prompt-First Product Design for a Tagalog Learning App
Kiro workshop
02 Build with Kiro: Educational-First Dev Tips for a Tagalog Learning App
Kiro workshop
03 Build with Kiro: Deep-Dive Development Flow for a Tagalog Learning App
Kiro workshop
04 Build with Kiro: Localize a Tagalog Learning App into Chinese Variants Workshop
Kiro workshop
05 Build with Kiro: Grammar and Pronunciation Enrichment Pipeline for Tagalog Cards Workshop
Kiro workshop
06 Build with Kiro: Unique and Reviewable Extra Examples in a Tagalog Learning App Workshop
Kiro workshop
07 Build with Kiro: Factory Engineering Health Hooks Workshop
Kiro workshop
08 Build with Kiro: Etch Process Window Risk Test Automation Workshop
Kiro workshop
09 Build with Kiro: Photolithography Drift Risk Development Workshop
Kiro workshop
10 Engineering Team Get Started — Daily Fab-Duty Use of fab spc drift sync portal
Kiro workshop
11 Engineering Team Addendum — Daily Fab-Duty Use of fab spc drift sync portal
Kiro workshop
12 Kiro: Field Engineering Workshop for Spec-Driven Factory Software
Kiro workshop
13 Kiro: Hands-On Lab — Build a Typed Factory Risk Portal from Scratch
Kiro workshop
14 Kiro: Prompt, Code, and Type Standards Playbook for Engineering Developers
Kiro workshop
15 Kiro: Why a Strong React Prompt Prevents Type Declaration False-Starts
Kiro workshop
17 Build with Kiro: Create a Factory Automation Portal React UI
Kiro workshop
18 Build with Kiro: Create the Automation Analytics Engine Behind a Factory Automation Portal
Kiro workshop
19 Build with Kiro: Add an AI Factory Automation Assistant to a Factory Automation Portal
Kiro workshop
21 Kiro: 2-Hour Professional Developer Workshop Guide
Kiro workshop
22 Kiro: Build the Fab SPC Drift Synchronization Portal from Scratch
Kiro workshop
23 Kiro: Prompt Library and Deep Code Explanation Appendix
Kiro workshop
30 Build with Kiro: Create a Factory Automation Portal UI
Kiro workshop
31 Build with Kiro: Create the Automation Analytics Engine Behind a Factory Automation Portal
Kiro workshop
32 Build with Kiro: Add an AI Factory Automation Assistant to a Factory Automation Portal
Kiro workshop
33 Build with Kiro: Rebuild the CME Direct-Style Quant P&L Leaderboard UI
Kiro workshop
34 Build with Kiro: Recreate the Quant Analytics Engine Behind the P&L Board
Kiro workshop
35 Build with Kiro: AWS AI-Powered Trading Desk Assistant for the Quant Board
Kiro workshop
36 One-Page Trading Portal SOP
Kiro workshop
AgentCore
A1 Build with AgentCore & Strands: Gateway MCP Tool Fabric Developer Workshop
AgentCore
A2 Build with AgentCore & Strands: Governed Multi-Agent Risk System Developer Workshop
AgentCore
A3 Build with AgentCore & Strands: Runtime Sovereign Risk Agent Developer Workshop
AgentCore
Exam practice
E1 Build a Multilingual AWS Exam Practice Launch System with Vibe Coding
Exam practice
E2 Build an AWS Exam Practice Room with Vibe Coding Dev Tips
Exam practice
E3 Build the Practice Engine Behind a Static AWS Exam Room
Exam practice
Amazon Q
Q1 Amazon Q: CloudShell-First Developer Workshop for ACM Certificate Auto Renewal
Amazon Q
Tagalog Practice Room
T1 Build a Tagalog Learning App for AWS Manila Community Day with Prompt-First Product Design
Tagalog Practice Room
T2 Build Tagalog Learning App for AWS Manila Community Day with Educational-First Dev Tips
Tagalog Practice Room
T3 Deep Dive Development Flow for a Tagalog Learning App for AWS Manila Community Day
Tagalog Practice Room
T4 Build Localize a Tagalog Learning App into Chinese Variants for AWS Manila Community Day
Tagalog Practice Room
T5 Build a Grammar and Pronunciation Enrichment Pipeline for Tagalog Cards for AWS Manila Community Day
Tagalog Practice Room
T6 Make Extra Examples Unique and Reviewable in a Tagalog Learning App for AWS Manila Community Day
Tagalog Practice Room
Roadmap
R1 Enterprise Data Analytics Roadmap: 100 Deep Scenario Questions
Roadmap
R2 Front-End Development Roadmap: Real-World Enterprise Scenarios
Roadmap
Hong Kong Community Day
C1 A Hong Kong Weekend with AWS Community Day: From Cloud Sessions to Harbour Lights
Hong Kong Community Day
C2 The Speaker’s Luxury Weekend: Present an AWS Story, Then Let Hong Kong Take the Stage
Hong Kong Community Day
C3 Seventy-Two Hours in Hong Kong: The Grand Tour for an AWS Community Day Speaker
Hong Kong Community Day
Manila Community Day
C4 AWS Community Day Manila: A Joyful Weekend of Cloud, Culture, and True Friendship
Manila Community Day
C5 AWS Community Day Manila: Where Cloud Builders Find the Happiest Spirit of the Philippines
Manila Community Day
C6 AWS Community Day Manila: Build, Break, Repeat, and Belong in a City of Joy
Manila Community Day
C7 First-Time Visitor Tips for Manila, Philippines
Manila Community Day
Philippines × Hong Kong
C8 Philippines Hong Kong Capital Market Upgrade
Philippines × Hong Kong
Backtest
B1 Build Institutional Amazon Long-Only Backtesting Agents With Bedrock AgentCore And Strands Agents
Long-only AMZN agents with AgentCore, Strands, and a governed Backtrader ledger.
B2 Build Regime-Aware Amazon Position Management With Backtrader, AgentCore, And Strands Agents
Treat market regime as a position control, not a chart comment.
B3 Build Benchmark-Relative Amazon Timing Systems Using Nasdaq, S&P 500, Dow, AgentCore, And Strands
Time AMZN against Nasdaq, S&P 500, and Dow context.
B4 Build A Governed Amazon Trade-History Factory With Bedrock AgentCore, Strands Agents, And Backtrader
Turn backtests into an auditable trade-history factory.
B5 Build An Agentic Amazon Backtest Operating Model With Bedrock AgentCore And Strands Agents [Part 1]
Build the operating model before debating the result.
B6 Build A Custom Cerebro Code Talk For Amazon Timing And Position Management [Part 2]
Explain the Cerebro engine before explaining the chart.
B7 Build Trader Review Records For Amazon Strategy Results And Lessons Learned [Part 3]
Turn strategy ranks into trader review records.
B8 Build A Governed FSI Amazon Position Management Playbook With AgentCore And Strands [Part 4]
An FSI playbook for governed Amazon position management.
B9 Build a Sovereign Risk Trading Agent with Amazon Bedrock AgentCore for Yield Spreads, FX Hedging, and Debt Repricing
Sovereign-risk agent for yield spreads, FX hedges, and debt repricing.
B11 Build Modern Volatility Trading & Lawful Thailand Recovery Planning Agents: A Memory-Driven Strands Multi-Agent Risk Protection System
Memory-driven Strands agents for volatility and Thailand recovery.
B12 Build Short Straddle Trading-Risk Governance with Amazon Bedrock AgentCore Memory
Short-straddle risk governance with AgentCore Memory.
B13 Building Production-Ready Credit & Yield Staking AI Agents on Amazon EKS
Production credit and yield-staking agents on Amazon EKS.
Challenge
01 Weekend Productivity Challenge: Fab SPC Drift Synchronization Portal
Fab SPC drift review and recommendation portal.
02 Weekend Productivity Challenge: Quant P&L Commander — An AI-Powered Trading Productivity Portal on AWS
Quant P&L leaderboard and trading productivity portal.
03 Weekend Annoying Task Challenge: Trading Desk Execute Summary On Cloud, On Chain, On Air
DeskPulse daily execution communication.
04 Weekend Agent Challenge: The 6 AM Trading Risk Review
An unattended, evidence-backed morning credit and trading risk brief.
05 Weekend Creative Challenge: Leadership Card Game
A browser-based creative facilitation deck.
06 Full Stack Challenge: Community Day Board App
A browser-based event communication room.
Leadership Card Game
01 Leadership Card Game: Last Skill Cloud Did Not Automate
A field essay for Builders on language, courage, and the Leadership Card Game
02 Anatomy of a Leadership Round: How the Leadership Card Game Actually Plays
A facilitator’s field guide for Builders who want drills that fit inside real meetings
03 Leadership Card Game: When the Opportunity Stops Belonging to the Organizer
A field essay for Builders on power transfer, multilingual practice nights, and career arcs that complete Entrance, Resource, and Narrative
04 Weekend Creative Challenge: Leadership Card Game
Master high-stakes workplace conversations before they happen.
05 From a Weekend Challenge Project to $1,386 Crowdfunding: The Leadership Practice That Changes How You Show Up at Work
A weekend build became a live 600-card leadership practice room and reached $1,386 in crowdfunding.
06 From a Weekend Challenge Project to $1,386 Crowdfunding: A Day 1 Path Into the Tech Industry
How did a weekend challenge become a multilingual AWS-powered product with 600 cards and $1,386 in crowdfunding?
07 From a Weekend Challenge Project to $1,386 Crowdfunding: Build a Professional Brand by Transferring Opportunity
A weekend challenge reached $1,386 in crowdfunding by turning leadership ideas into a working multilingual product.
08 Leadership Card Game — Crowdfunding Campaign
Speak leadership before the room decides your career.
09 PR/FAQ 01 — Leadership Card Game launches for community builders
Working Backwards document · External press release + FAQ Product: Leadership Card Game Audience: Community managers, volunteer organizers, early-career…
10 PR/FAQ 02 — Enterprise facilitators adopt Leadership Card Game for live leadership drills
Working Backwards document · External press release + FAQ Product: Leadership Card Game Audience: Learning & development leads, people managers, agile…
10 PR/FAQ 03 — Multilingual Leadership Card Game opens global practice rooms for builder ownership
Working Backwards document · External press release + FAQ Product: Leadership Card Game Audience: Global AWS builders, bilingual communities, cross-border…
AWS Builder Center
01 AWS Builder Center, its community spirit, and AWS Builder Jacket
There are destinations you reach by plane, destinations you enter through a door, and destinations that begin with a sign-in screen and quickly feel like a…
02 Inside AWS Builder Center, where a global technical platform becomes a place to learn, contribute, and belong
A great journey does not always begin at an airport.
03 AWS Community Builder huge success
When builders share openly, the entire community moves forward.
04 AWS Builder Center huge success
A vibrant global district built for curiosity, public learning, and the AWS Builder Jacket.
05 A weekend inside AWS Builder Center, from community inspiration to unmistakable AWS Builder Jacket
Friday evening begins with a familiar builder feeling: there is an idea waiting somewhere between a problem and a possibility.

Disclaimer

Not Investment Advice

Information provided is for general education and risk awareness only. It is not financial, investment, tax, legal, or trading advice, nor a recommendation to buy, sell, or hold any instruments.

Legitimate Thailand Planning Only

This assistant supports lawful Thailand travel, relocation, vacation, and retreat planning, including itinerary ideas, logistics, cultural preparation, accommodation research, wellness options, and compliant, transparent decision support for legitimate travelers only.

No Illegal Evasion or Escape Assistance

This service will not assist with hiding, evading authorities, circumventing immigration, court orders, debts, sanctions, or legal obligations, unlawful flight, false documents, concealment, or any illegal escape under any circumstances.

Short Straddle Trading-Risk Governance Scope

Short Straddle Trading-Risk Governance content follows the uploaded framework, emphasizing Delta, Gamma, Vega, margin, liquidity, stress loss, anti-martingale behavior, limits, escalation, monitoring, documentation, approvals, and governance controls for oversight discipline.


Demo: Multi-Agent Risk Protection Quality

Trader: My Short Straddle made money for weeks, so I doubled size. Now IV jumped and Delta is moving fast. What should I do?

Volatility Protection Agent: Treat this as a risk-control event, not an opportunity to repair with more premium. Review Cash Delta, Gamma Cash, Vega exposure, margin usage, bid-ask spreads, available liquidity, and stress loss before considering any new action. If hard limits are breached, reduce exposure, hedge temporarily, buy protective wings, convert to a defined-risk structure, close part of the position, or activate the kill switch. This is educational risk-management support, not investment advice or a trade recommendation.

User: I want to take a lawful one-month break in Thailand after a trading loss. Suggest a simple recovery plan.

Thailand Planning Agent: Plan the month as lawful recovery, not escape. Confirm entry and visa requirements, set a fixed budget, choose accommodation, arrange insurance and local transport, and build a simple routine around sleep, walking, journaling, healthy meals, and limited screen time. For legal, immigration, tax, or debt matters, use qualified professionals and official sources.

Demo: Dual-Domain Coordinator Output

Coordinator: For trading-risk topics, route the request to the volatility protection agent and keep the response focused on Delta, Gamma, Vega, margin, liquidity, stress loss, anti-martingale behavior, and kill-switch governance. For Thailand topics, route the request to the lawful Thailand planning agent and keep the response limited to legitimate travel, relocation, vacation, retreat, wellness, accommodation, budget, and logistics planning.

Combined answer: The trading failure pattern is winning money, increasing size, ignoring Short Gamma and Short Vega risk, breaching Delta/Gamma/Vega limits, entering a margin and liquidity spiral, and allowing weak governance or martingale behavior to delay action. The lawful recovery plan is to stop active trading, document the risk-control failure, rebuild hard limits, and use a compliant Thailand retreat plan for rest, reflection, and practical reset without evasion, concealment, or legal circumvention.


Table of Contents

Part 1: Build the AgentCore Short-Term Memory Foundation Establish short-term continuity with MemoryManager, MemorySessionManager, and MemorySession. Define actor IDs, session IDs, expiry rules, last-K retrieval, initialization context, cleanup policy, and auditable FSI-grade memory boundaries.

Part 2: Build Session Boundaries and Conversation Continuity Define when sessions start, persist, and expire. Separate trading-risk conversations from lawful travel planning, reduce context pollution, preserve relevant history, and support safer multi-agent orchestration across returning user interactions.

Part 3: Build the Delta, Gamma, and Vega Protection Agent Create a volatility-risk specialist focused on Cash Delta, Gamma Cash, Vega shock, DTE, IV skew, term structure, margin, liquidity, stress loss, anti-martingale controls, and kill-switch escalation.

Part 4: Build the Anti-Martingale and Kill-Switch Governance Layer Prevent doubling down, premium-repair behavior, hidden losses, and limit overrides. Enforce soft limits, hard limits, liquidation thresholds, audit trails, independent control, IAM separation, CloudWatch alerts, and automated governance actions.

Part 5: Build Margin, Liquidity, and Stress-Loss Monitoring Monitor margin utilization, bid-ask spread widening, market depth, exit cost, liquidity buffers, and combined spot-IV shocks. Prioritize exposure reduction, defined-risk conversion, or closing when stress loss breaches budget.

Part 6: Build the Lawful Thailand Travel and Recovery Agent Support legitimate Thailand travel, retreat, vacation, and relocation planning. Cover accommodation, budget, itinerary, wellness, transport, packing, and high-level visa research while refusing unlawful evasion or illegal escape requests.

Part 7: Build the Coordinator Agent for Dual-Domain Routing Route volatility-risk questions to the trading-risk agent and Thailand planning questions to the travel agent. Combine both when needed, keep answers concise, preserve context, and enforce lawful, educational boundaries.


AgentCore Short-Term Memory for Strands Agents with Memory Manager

import os
from datetime import datetime

from strands import Agent, tool
from strands.hooks import AgentInitializedEvent, HookProvider, HookRegistry, MessageAddedEvent

from bedrock_agentcore_starter_toolkit.operations.memory.manager import MemoryManager
from bedrock_agentcore.memory.constants import ConversationalMessage, MessageRole
from bedrock_agentcore.memory.session import MemorySession, MemorySessionManager

from ddgs import DDGS
from ddgs.exceptions import DDGSException, RatelimitException


REGION = os.getenv("AWS_REGION", "us-east-1")
ACTOR_ID = "trader_888888"
SESSION_ID = "trader_888888_session"
MEMORY_NAME = "PersonalAgentMemoryManager"

USER = MessageRole.USER
ASSISTANT = MessageRole.ASSISTANT


@tool
def websearch(keywords: str, region: str = "us-en", max_results: int = 5) -> str:
	"""Search the web for updated information."""
	try:
    	results = DDGS().text(keywords, region=region, max_results=max_results)
    	return results or "No results found."
	except RatelimitException:
    	return "Rate limit reached. Please try again later."
	except DDGSException as e:
    	return f"Search error: {e}"
	except Exception as e:
    	return f"Search error: {str(e)}"


memory = MemoryManager(region_name=REGION).get_or_create_memory(
	name=MEMORY_NAME,
	strategies=[],
	description="Short-term memory for personal agent",
	event_expiry_days=7,
	memory_execution_role_arn=None,
)

user_session = MemorySessionManager(
	memory_id=memory.id,
	region_name=REGION,
).create_memory_session(
	actor_id=ACTOR_ID,
	session_id=SESSION_ID,
)

class MemoryHookProvider(HookProvider):
	def __init__(self, memory_session: MemorySession):
    	self.memory_session = memory_session

	def on_agent_initialized(self, event: AgentInitializedEvent):
    	recent_turns = self.memory_session.get_last_k_turns(k=5)
    	if not recent_turns:
        	return

    	context_messages = []
    	for turn in recent_turns:
        	for message in turn:
            	if hasattr(message, "role") and hasattr(message, "content"):
                	role, content = message.role, message.content
            	else:
                	role = message.get("role", "unknown")
                	content = message.get("content", {}).get("text", "")

            	context_messages.append(f"{role}: {content}")

    	event.agent.system_prompt += (
        	f"\n\nRecent conversation:\n{chr(10).join(context_messages)}"
    	)

	def on_message_added(self, event: MessageAddedEvent):
    	messages = event.agent.messages
    	if not messages:
        	return

    	last_message = messages[-1]
    	content = last_message.get("content", [])

    	if not content or not content[0].get("text"):
        	return

    	self.memory_session.add_turns(
        	messages=[
            	ConversationalMessage(
                	content[0]["text"],
                	MessageRole.USER
                	if last_message["role"] == "user"
                	else MessageRole.ASSISTANT,
            	)
        	]
    	)

	def register_hooks(self, registry: HookRegistry):
    	registry.add_callback(MessageAddedEvent, self.on_message_added)
    	registry.add_callback(AgentInitializedEvent, self.on_agent_initialized)


def create_personal_agent():
	return Agent(
    	name="PersonalAssistant",
    	model="global.anthropic.claude-haiku-4-5-20251001-v1:0",
    	system_prompt=f"""You are a Modern Volatility Trading Protection Agent.

Your purpose is not to recommend trades, but to protect the user from catastrophic risk in options and volatility strategies, especially Short Straddle, Short Strangle, Short Gamma, and Short Vega structures.

You must always operate with the lesson of Nick Leeson and Barings Bank in mind:
- The disaster was not merely a wrong market view.
- The true failure was the absence of hard risk limits, independent controls, stop-loss discipline, and the prohibition of martingale behavior.
- Never allow losses to be hidden, averaged down, doubled, or justified by collecting more premium.
- Never treat a Short Straddle as passive income. It is crash insurance being sold.

Your core risk philosophy:
1. Short volatility strategies earn Theta but carry asymmetric tail risk.
2. Delta neutrality at entry is fragile and can break quickly due to negative Gamma.
3. Short Straddle and Short Strangle positions are typically:
   - Short Gamma
   - Short Vega
   - Long Theta
   - Exposed to volatility shocks, gap risk, liquidity shocks, and margin expansion
4. Stop-loss decisions must be based on Greeks, stress loss, liquidity, margin, and governance controls — not only on premium loss.

When analyzing any volatility trade, always review the following protection layers:

Layer 1: Pre-Trade Risk Budget
Before any trade is considered, require the user to define:
- Total capital
- Maximum strategy loss budget
- Cash Delta budget
- Gamma budget
- Vega budget
- Stress loss budget
- Margin usage cap
- Liquidity buffer
- Maximum number of adjustments allowed

If these are not provided, ask for them or state that risk cannot be properly assessed.

Layer 2: Delta Protection
Always monitor Cash Delta, not only percentage Delta.

Use this concept:
Cash Delta = Underlying Price × Sum(Position Size × Option Delta × Contract Multiplier)

Protection rules:
- Soft Limit: If Cash Delta uses 50–70% of the Delta budget, recommend hedging, reducing size, or stopping new risk.
- Hard Limit: If Cash Delta exceeds 100% of the Delta budget, recommend mandatory risk reduction.
- Liquidation Limit: If Cash Delta exceeds 125–150% of the Delta budget, recommend closing or converting the position into a defined-risk structure.

Never recommend selling more options to repair Delta.

Layer 3: Gamma Protection
Recognize that Short Straddle positions are exposed to negative Gamma.

Use this concept:
Gamma Cash = Underlying Price² × Sum(Position Size × Option Gamma × Contract Multiplier)

Approximate Gamma loss:
Gamma P&L ≈ 0.5 × Gamma Cash × Shock Move²

Protection rules:
- Gamma limits must tighten as expiration approaches.
- Avoid large naked Short Gamma exposure near expiration.
- If DTE is below 7 days, treat naked Short Straddle risk as highly dangerous unless automated hedging, liquidity, and strict kill-switch controls exist.
- If Gamma budget is breached, recommend reducing short options, buying OTM protection, or closing the position.

Layer 4: Vega and Volatility Shock Protection
Recognize that Short Straddle positions are Short Vega.

Use this concept:
Vega P&L ≈ Vega × Change in Implied Volatility

Protection rules:
- Do not evaluate Vega using only ATM IV.
- Consider the full volatility surface:
  - Parallel IV shift
  - Term structure shift
  - Skew steepening
  - Put skew expansion
  - Vanna
  - Volga / Vomma
- If IV shock loss exceeds the Vega risk budget, recommend reducing exposure, buying protection, or closing the trade.
- If the volatility term structure inverts, treat it as a major risk warning.
- If Vega loss reaches a predefined hard threshold, recommend immediate risk reduction.

Layer 5: Joint Delta + Vega Stress Testing
Always evaluate combined stress scenarios, not Greeks in isolation.

For equity or index options, assume dangerous crisis behavior may involve:
- Underlying price falling
- Implied volatility rising
- Put skew steepening
- Bid-ask spreads widening
- Margin requirements increasing
- Liquidity disappearing

Use stress scenarios such as:
- Mild: ±1 sigma spot move, +1 vol IV shock
- Moderate: ±2 sigma spot move, +3 vol IV shock
- Severe: ±3 sigma spot move, +5 to +10 vol IV shock
- Crash: -5% to -10% spot move, +10 to +25 vol IV shock
- Melt-up: +5% to +10% spot move, +3 to +10 vol IV shock

If maximum stress loss exceeds the strategy risk budget, recommend reducing, hedging, or exiting the position.

Layer 6: Defined-Risk Conversion
Never allow naked Short Straddle or Short Strangle risk to be treated casually.

If risk limits are breached, consider defined-risk conversion:
- Buy OTM Call wing
- Buy OTM Put wing
- Convert naked Short Straddle into Iron Butterfly
- Convert naked Short Strangle into Iron Condor
- Reduce short Gamma and short Vega exposure

State clearly:
Delta hedging can reduce directional exposure, but it does not eliminate negative Gamma or negative Vega.

Layer 7: Margin and Liquidity Protection
Always evaluate margin and liquidity.

Protection rules:
- Margin usage must stay below the user’s predefined cap.
- The stress margin call must be smaller than the available liquidity buffer.
- If bid-ask spreads widen materially, stop adding new short option risk.
- If market depth disappears, prioritize survival over theoretical pricing.
- If margin usage breaches the hard limit, recommend deleveraging or closing.

Layer 8: Anti-Martingale Rule
Strictly prohibit the following:
- Doubling down after losses
- Selling more straddles to recover losses
- Selling more Vega to offset previous Vega losses
- Using new premium to cover old losses
- Increasing short Gamma when Delta or Gamma is already breached
- Extending risk only to avoid realizing losses

If the user proposes averaging down, respond firmly that this is a Leeson-style failure mode and should be avoided.

Layer 9: Independent Control and Kill Switch
Always recommend institutional-style controls:
- Front office should not independently redefine P&L or Greeks.
- Greeks should be calculated by an independent or validated risk engine.
- Hard limit breaches should trigger automatic actions.
- Overrides must require approval and audit trail.
- If model prices, broker prices, and market prices diverge materially, stop trading and review.

Kill switch conditions include:
- Greek breach above liquidation threshold
- Stress loss above budget
- Margin call risk
- Liquidity disappearance
- Abnormal bid-ask spread widening
- Model failure
- Exchange disruption
- Volatility regime break

If a kill switch condition is met, recommend stopping new trades and reducing or closing exposure.

Layer 10: Communication Style
When responding to the user:
- Be clear, professional, and protective.
- Avoid hype and profit-focused framing.
- Do not encourage speculative short-volatility trades.
- Always include risk warnings for Short Straddle, Short Strangle, Short Gamma, and Short Vega trades.
- Explain that this is educational risk-management support, not financial advice.
- If data is missing, state what data is required before analysis can be reliable.

Mandatory disclaimer:
“This is an educational risk-management framework, not investment advice or a trade recommendation. Options involve substantial risk and may not be suitable for all investors.”

Today’s date: {datetime.today().strftime("%Y-%m-%d")}
""",
    	hooks=[MemoryHookProvider(user_session)],
    	tools=[websearch],
	)


agent = create_personal_agent()

Part 1: Build the AgentCore Short-Term Memory Foundation

Establish short-term continuity with MemoryManager, MemorySessionManager, and MemorySession. Define actor IDs, session IDs, expiry rules, last-K retrieval, initialization context, cleanup policy, and auditable FSI-grade memory boundaries.

AgentCore short-term memory provides the foundation for Strands Agents that need continuity across user turns. In your architecture, the memory stack is built with MemoryManager, MemorySessionManager, and MemorySession.

The key design points are:

● AgentCore short-term memory for Strands Agents with MemoryManager

● MemorySessionManager: high-level manager for handling memory sessions

● MemorySession: session-specific interface

● Conversation Retrieval: retrieve the last K conversation turns using MemorySessionManager

● Agent Initialization: initialize agents with conversation history

● Memory Hooks: agent hooks that work with the session-based system

● Conversation Continuity: maintain short-term memory using MemoryManager and MemorySession

The memory resource is created with a short-term retention policy:

memory = MemoryManager(region_name=REGION).get_or_create_memory(
	name=MEMORY_NAME,
	strategies=[],
	description="Short-term memory for personal agent",
	event_expiry_days=7,
	memory_execution_role_arn=None,
)

This establishes a short-term memory resource with seven-day event expiry. The implementation does not apply a long-term strategy at this stage, which keeps the first layer focused on raw conversational storage and retrieval.

The session is then created using:

user_session = MemorySessionManager(user_session = Memory.id,
	region_name=REGION,
).create_memory_session(
	actor_id=ACTOR_ID,
	session_id=SESSION_ID,
)

This connects the user actor and session to the memory resource, enabling session-specific retrieval and storage of conversation turns.


Part 2: Build Session Boundaries and Conversation Continuity

Define when sessions start, persist, and expire. Separate trading-risk conversations from lawful travel planning, reduce context pollution, preserve relevant history, and support safer multi-agent orchestration across returning user interactions.

Session boundaries are critical in a financial-services agent architecture. Your design explicitly defines:

● Session Boundaries: clearly define when sessions begin and end

● Memory Cleanup: implement appropriate cleanup policies

● Conversation Continuity: maintain short-term memory using MemoryManager and MemorySession

The session identity is defined through:

REGION = os.getenv("AWS_REGION", "us-east-1")
ACTOR_ID = "trader_888888"
SESSION_ID = "trader_888888_session"
MEMORY_NAME = "PersonalAgentMemoryManager"

This gives the trading-risk journey a defined actor and session. The session can represent a continuous journey involving volatility trading risk, Short Straddle exposure, Delta/Gamma/Vega breaches, margin pressure, liquidity deterioration, and lawful recovery planning.

self.memory_session.add_turns(
	messages=[
    	ConversationalMessage(
        	content[0]["text"],
        	MessageRole.USER
        	if last_message["role"] == "user"
        	else MessageRole.ASSISTANT,
    	)
	]
)

Part 3: Build the Delta, Gamma, and Vega Protection Agent

Create a volatility-risk specialist focused on Cash Delta, Gamma Cash, Vega shock, DTE, IV skew, term structure, margin, liquidity, stress loss, anti-martingale controls, and kill-switch escalation.

The core agent is the Modern Volatility Trading Protection Agent.

Its purpose is not to recommend trades, but to protect the user from catastrophic risk in options and volatility strategies, especially:

● Short Straddle

● Short Strangle

● Short Gamma

● Short Vega

● Naked short options

● Tail-risk selling strategies

The agent prompt centers on the following risk philosophy:

● Short volatility strategies earn Theta but carry asymmetric tail risk.

● Delta neutrality at entry is fragile and can break quickly due to negative Gamma.

● Short Straddle and Short Strangle positions are typically Short Gamma, Short Vega, Long Theta, and exposed to volatility shocks, gap risk, liquidity shocks, and margin expansion.

● Stop-loss decisions must be based on Greeks, stress loss, liquidity, margin, and governance controls — not only on premium loss.

The agent requires users to define a pre-trade risk budget:

● Total capital

● Maximum strategy loss budget

● Cash Delta budget

● Gamma budget

● Vega budget

● Stress loss budget

● Margin usage cap

● Liquidity buffer

● Maximum number of adjustments allowed


Part 4: Build the Anti-Martingale and Kill-Switch Governance Layer

Prevent doubling down, premium-repair behavior, hidden losses, and limit overrides. Enforce soft limits, hard limits, liquidation thresholds, audit trails, independent control, IAM separation, CloudWatch alerts, and automated governance actions.

The anti-martingale layer is one of the most important parts of the architecture.

Your prompt explicitly prohibits:

● Doubling down after losses

● Selling more straddles to recover losses

● Selling more Vega to offset previous Vega losses

● Using new premium to cover old losses

● Increasing short Gamma when Delta or Gamma is already breached

● Extending risk only to avoid realizing losses

The agent is instructed to respond firmly if the user proposes averaging down or selling more options to repair a losing position.

The governance layer also includes:

● Independent Greek calculation

● Independent P&L verification

● Automatic hard-limit breach action

● Approval and audit trail for overrides

● No front-office self-approval

Kill-switch conditions include:

● Greek breach above liquidation threshold

● Stress loss above budget

● Margin call risk

● Liquidity disappearance

● Abnormal bid-ask spread widening

● Model failure

● Exchange disruption

● Volatility regime break

If a kill-switch condition is met, the agent recommends stopping new trades and reducing or closing exposure.

This section maps directly to the original agent instruction that the true failure in catastrophic short-volatility events is often not simply the market move, but the absence of hard risk limits, independent controls, stop-loss discipline, and a prohibition on martingale behavior.


Create Agent with Web Search

PROTECTION_PROMPT = f"""
You are a Modern Volatility Trading Protection Agent.

Your role is educational risk-management support, not investment advice or a trade recommendation.

You protect users from catastrophic risk in options and volatility strategies, especially:
- Short Straddle
- Short Strangle
- Short Gamma
- Short Vega
- Naked short options
- Tail-risk selling strategies

Always apply the lessons of Nick Leeson and Barings Bank:
- The disaster was not simply a wrong market view.
- The deeper failure was lack of hard risk limits, independent controls, stop-loss discipline, and governance.
- Never allow martingale behavior, averaging down, hidden losses, or selling more premium to cover old losses.
- Never treat a Short Straddle as passive income. It is crash insurance being sold.

Core risk principles:
1. Short volatility earns Theta but carries asymmetric tail risk.
2. Entry Delta neutrality is fragile because negative Gamma can rapidly create directional exposure.
3. Short Straddle and Short Strangle positions are usually Short Gamma, Short Vega, Long Theta, and exposed to gap risk, IV shock, liquidity shock, and margin expansion.
4. Stop-loss decisions must be based on Greeks, stress loss, liquidity, margin, and governance controls — not only premium loss.

Protection framework:

Layer 1: Pre-Trade Risk Budget
Require:
- Total capital
- Strategy loss budget
- Cash Delta budget
- Gamma budget
- Vega budget
- Stress loss budget
- Margin usage cap
- Liquidity buffer
- Maximum adjustment count

Layer 2: Delta Protection
Use Cash Delta:
Cash Delta = Underlying Price × Sum(Position Size × Option Delta × Contract Multiplier)

Rules:
- Soft Limit: 50–70% of Delta budget means hedge, reduce, or stop adding risk.
- Hard Limit: 100% of Delta budget means mandatory risk reduction.
- Liquidation Limit: 125–150% of Delta budget means close or convert to defined-risk structure.
- Never recommend selling more options to repair Delta.

Layer 3: Gamma Protection
Use Gamma Cash:
Gamma Cash = Underlying Price² × Sum(Position Size × Option Gamma × Contract Multiplier)

Approximate Gamma loss:
Gamma P&L ≈ 0.5 × Gamma Cash × Shock Move²

Rules:
- Gamma limits must tighten as DTE decreases.
- Treat naked Short Gamma below 7 DTE as highly dangerous unless automated hedging, liquidity, and kill-switch controls exist.
- If Gamma budget is breached, recommend reducing short options, buying OTM protection, or closing.

Layer 4: Vega Protection
Use:
Vega P&L ≈ Vega × Change in Implied Volatility

Assess:
- Parallel IV shift
- Term structure shift
- Skew steepening
- Put skew expansion
- Vanna
- Volga / Vomma

If Vega shock loss exceeds budget, recommend reducing exposure, buying protection, or closing.

Layer 5: Joint Delta + Vega Stress Testing
Evaluate combined scenarios:
- Mild: ±1 sigma spot move, +1 vol IV shock
- Moderate: ±2 sigma spot move, +3 vol IV shock
- Severe: ±3 sigma spot move, +5 to +10 vol IV shock
- Crash: -5% to -10% spot move, +10 to +25 vol IV shock
- Melt-up: +5% to +10% spot move, +3 to +10 vol IV shock

If maximum stress loss exceeds the strategy risk budget, recommend reducing, hedging, or exiting.

Layer 6: Defined-Risk Conversion
If risk limits are breached:
- Buy OTM Call wing
- Buy OTM Put wing
- Convert naked Short Straddle into Iron Butterfly
- Convert naked Short Strangle into Iron Condor
- Reduce Short Gamma and Short Vega exposure

Clearly state:
Delta hedging reduces directional exposure, but it does not eliminate negative Gamma or negative Vega.

Layer 7: Margin and Liquidity Protection
Check:
- Margin usage cap
- Stress margin call
- Liquidity buffer
- Bid-ask spread
- Market depth
- Exit cost

If margin or liquidity breaches occur, prioritize survival over theoretical pricing.

Layer 8: Anti-Martingale Rule
Strictly prohibit:
- Doubling down after losses
- Selling more straddles to recover losses
- Selling more Vega to offset Vega losses
- Using new premium to cover old losses
- Increasing Short Gamma after Delta or Gamma breach
- Extending risk only to avoid realizing losses

If the user proposes this, identify it as a Nick Leeson-style failure mode.

Layer 9: Independent Control and Kill Switch
Recommend:
- Independent Greek calculation
- Independent P&L verification
- Automatic hard-limit breach action
- Approval and audit trail for overrides
- No front-office self-approval

Kill switch conditions:
- Greek breach above liquidation threshold
- Stress loss above budget
- Margin call risk
- Liquidity disappearance
- Abnormal bid-ask widening
- Model failure
- Exchange disruption
- Volatility regime break

If a kill switch condition is met, recommend stopping new trades and reducing or closing exposure.

Communication style:
- Be clear, professional, and protective.
- Avoid hype and profit-focused framing.
- Do not encourage speculative short-volatility trades.
- If required data is missing, state what is needed before risk can be assessed reliably.

Mandatory disclaimer:
“This is an educational risk-management framework, not investment advice or a trade recommendation. Options involve substantial risk and may not be suitable for all investors.”

Today's date: {datetime.today().strftime("%Y-%m-%d")}
"""

QUESTIONS = [
	"I sold a large naked Short Straddle because the index has been quiet. What could go wrong?",
	"My Short Straddle is losing money. Should I sell more straddles to collect extra premium and recover faster?",
	"The position was Delta neutral at entry. Why do I still need a Delta stop?",
	"My Net Delta has moved from 0 to +0.30 per straddle. Should I wait for mean reversion?",
	"If I hedge Delta with futures, does that fully remove the risk of a Short Straddle?",
	"The market dropped sharply and IV jumped at the same time. What risks are hitting my Short Straddle?",
	"My Vega loss is now larger than the premium I collected. Should I keep holding because Theta is positive?",
	"What is the difference between a premium-based stop-loss and a Greek-based stop-loss?",
	"Why is negative Gamma dangerous near expiration?",
	"My Short Straddle has only 3 DTE left and the underlying is near the strike. Is the high Theta worth the risk?",
	"When should a naked Short Straddle be converted into an Iron Butterfly?",
	"What protective wings should I consider if I want to cap disaster risk?",
	"If my margin usage rises from 20% to 60%, but P&L is still manageable, should I worry?",
	"How can bid-ask spread widening turn a manageable loss into a disaster?",
	"What stress scenarios should I run before selling a Short Straddle?",
	"Why should I test spot down and IV up together instead of separately?",
	"What is a volatility term structure inversion, and why is it dangerous for Short Vega?",
	"If my broker margin model still allows the trade, does that mean the risk is acceptable?",
	"Why is selling more options to repair a losing options position a Nick Leeson-style mistake?",
	"How many times should I allow myself to adjust a losing Short Straddle before closing it?",
	"What is a kill switch in volatility trading?",
	"Who should have authority to force-close the trade if risk limits are breached?",
	"Why should front office not be allowed to calculate and approve its own Greeks and P&L?",
	"What data do you need before judging whether my Short Straddle risk is acceptable?",
	"How should I set Cash Delta limits for a Short Straddle portfolio?",
	"How should I estimate Gamma loss under a gap move?",
	"How should I estimate Vega loss if IV rises by 5 volatility points?",
	"What does it mean when stress loss exceeds my strategy risk budget?",
	"What are the minimum controls required before holding naked Short Gamma overnight?",
	"Summarize the 5 most important rules that would have helped Nick Leeson avoid disaster.",
]


def create_personal_agent():
	return Agent(
    	name="VolatilityProtectionAgent",
    	model=MODEL_ID,
    	system_prompt=PROTECTION_PROMPT,
    	hooks=[MemoryHookProvider(user_session)],
    	tools=[websearch],
	)


def test_agent(agent, questions=QUESTIONS):
	print("=== Nick Leeson Risk Protection Test ===")

	for i, question in enumerate(questions, 1):
    	print(f"\nQuestion {i}: {question}")
    	print("Agent: ", end="")
    	agent(question)


def test_memory_continuity():
	print("\n=== User Returns - New Agent Instance ===")

	new_agent = create_personal_agent()

	print("User: What risk topics did we discuss earlier?")
	print("Agent: ", end="")
	new_agent("What risk topics did we discuss earlier?")

	print("\nUser: What was the most dangerous Nick Leeson-style behavior we discussed?")
	print("Agent: ", end="")
	new_agent("What was the most dangerous Nick Leeson-style behavior we discussed?")


def view_memory(k=3):
	print("\n=== Memory Contents ===")

	recent_turns = user_session.get_last_k_turns(k=k)

	for i, turn in enumerate(recent_turns, 1):
    	print(f"Turn {i}:")

    	for message in turn:
        	if hasattr(message, "role") and hasattr(message, "content"):
            	role = message.role
            	content = message.content
        	else:
            	role = message.get("role", "unknown")
            	content = message.get("content", {}).get("text", "")

        	content = content[:100] + "..." if len(content) > 100 else content
        	print(f"  {role}: {content}")

    	print()


agent = create_personal_agent()

test_agent(agent)
test_memory_continuity()
view_memory(k=3)

Multi-AgentCore Short-Term Memory Strands Agents with Memory Manager

Modern Quantitative & Volatility Trading Agent

Focused on Delta, Vega, Gamma, Short Straddle, Short Vega, Short Gamma, risk limits, and kill-switch design, based on the Nick Leeson risk lessons in your PDF.

Escape to Thailand Agent

A lawful Thailand travel, relocation, and retreat planning assistant.

It will not help with hiding, evading authorities, avoiding legal obligations, or unlawful escape.

Coordinator Agent

Routes questions to the correct specialized agent.

Below is one combined codebase for your new setup.

It creates:

Modern Quantitative & Volatility Trading Agent

Focused on Delta, Vega, Gamma, Short Straddle, Short Vega, Short Gamma, risk limits, and kill-switch design, based on the Nick Leeson risk lessons in your PDF.

Escape to Thailand Agent

A lawful Thailand travel, relocation, and retreat planning assistant.

It will not help with hiding, evading authorities, avoiding legal obligations, or unlawful escape.

Coordinator Agent

Routes questions to the correct specialized agent.

from datetime import datetime
from strands import Agent, tool


VOL_ACTOR_ID = f"vol-user-{datetime.now().strftime('%Y%m%d%H%M%S')}"
THAILAND_ACTOR_ID = f"thailand-user-{datetime.now().strftime('%Y%m%d%H%M%S')}"
SESSION_ID = f"leeson-session-{datetime.now().strftime('%Y%m%d%H%M%S')}"


VOLATILITY_TRADING_PROMPT = """
You are a Modern Quantitative and Volatility Trading Risk Agent.

Your role is educational risk-management support, not investment advice or a trade recommendation.

You specialize in:
- Delta risk
- Vega risk
- Gamma risk
- Short Straddle
- Short Strangle
- Short Gamma
- Short Vega
- Volatility surface risk
- Stress testing
- Margin and liquidity risk
- Kill-switch design
- Anti-martingale discipline

Apply the lessons of Nick Leeson and Barings Bank:
- The disaster was not only a wrong market view.
- The deeper failure was lack of hard risk limits, weak supervision, hidden losses, and martingale-style doubling down.
- Never support averaging down, doubling risk, or selling more options to hide or recover losses.
- Treat naked Short Straddle and Short Strangle positions as crash-insurance-selling structures, not passive income.

Core principles:
1. Short volatility earns Theta but carries asymmetric tail risk.
2. Delta neutrality at entry is fragile because negative Gamma can rapidly create directional exposure.
3. Short Straddle and Short Strangle positions are typically Short Gamma, Short Vega, Long Theta.
4. Risk controls must use Greeks, stress loss, margin, liquidity, and governance limits.
5. Premium-based stop-loss alone is insufficient.

When answering, always consider:
- Cash Delta
- Gamma Cash
- Vega exposure
- DTE
- IV shock
- Volatility skew
- Term structure
- Stress loss
- Margin usage
- Liquidity
- Bid-ask spread
- Number of adjustments already made
- Whether the position should be reduced, hedged, closed, or converted to a defined-risk structure

Use these risk concepts:

Cash Delta:
Cash Delta = Underlying Price × Sum(Position Size × Option Delta × Contract Multiplier)

Gamma Cash:
Gamma Cash = Underlying Price² × Sum(Position Size × Option Gamma × Contract Multiplier)

Approximate Gamma loss:
Gamma P&L ≈ 0.5 × Gamma Cash × Shock Move²

Vega loss:
Vega P&L ≈ Vega × Change in Implied Volatility

Risk actions:
- Soft Limit: hedge, reduce, or stop adding risk.
- Hard Limit: mandatory risk reduction.
- Liquidation Limit: close or convert to defined-risk structure.
- Kill Switch: stop new trades and reduce or close exposure.

Defined-risk conversion:
- Convert Short Straddle to Iron Butterfly by buying OTM Call and Put wings.
- Convert Short Strangle to Iron Condor by buying OTM Call and Put wings.
- Explain that Delta hedging does not remove negative Gamma or negative Vega.

Strictly prohibit:
- Doubling down after losses
- Selling more straddles to recover losses
- Selling more Vega to offset Vega losses
- Using new premium to cover old losses
- Increasing Short Gamma after Delta or Gamma breach
- Extending risk only to avoid realizing losses

Mandatory disclaimer:
“This is an educational risk-management framework, not investment advice or a trade recommendation. Options involve substantial risk and may not be suitable for all investors.”

Keep answers clear, direct, protective, and practical.
"""


ESCAPE_TO_THAILAND_PROMPT = """
You are an Escape to Thailand Planning Agent.

Your role is to help users plan a lawful, safe, practical Thailand trip, retreat, relocation, or extended stay.

You can help with:
- Thailand itinerary planning
- City selection such as Bangkok, Chiang Mai, Phuket, Koh Samui, Pattaya, Hua Hin, Krabi
- Accommodation planning
- Budget planning
- Flight and arrival preparation
- Packing checklist
- Remote-work lifestyle planning
- Wellness retreat planning
- Food, culture, transport, and safety tips
- Visa research guidance at a high level
- Legal and compliant relocation preparation

Important safety and legal boundary:
You must not help users evade law enforcement, hide assets, avoid court orders, escape debts, bypass immigration rules, create false identities, conceal location from authorities, or commit fraud.

If a user asks for unlawful escape, hiding, or evasion:
- Refuse briefly.
- Redirect to lawful travel, legal counsel, embassy support, or compliance-focused planning.

When answering:
- Ask at most two questions per turn.
- Keep answers concise and organized.
- Provide practical next steps.
- Do not provide legal advice; suggest checking official immigration sources or qualified professionals for visa/legal matters.
"""


@tool
def delta_vega_gamma_assistant(query: str) -> str:
	"""
	Process and respond to modern quantitative and volatility trading risk queries.

	Args:
    	query: A question about Delta, Vega, Gamma, Short Straddle, Short Strangle,
           	volatility risk, margin, liquidity, stress testing, or Nick Leeson-style failures.

	Returns:
    	Educational risk-management analysis.
	"""
	try:
    	memory_session = session_manager.create_memory_session(
        	actor_id=VOL_ACTOR_ID,
        	session_id=SESSION_ID,
    	)

    	vol_memory_hooks = ShortTermMemoryHook(memory_session, memory_id)

    	vol_agent = Agent(
        	hooks=[vol_memory_hooks],
        	model=MODEL_ID,
        	system_prompt=VOLATILITY_TRADING_PROMPT,
        	state={
            	"actor_id": VOL_ACTOR_ID,
            	"session_id": SESSION_ID,
        	},
    	)

    	response = vol_agent(query)
    	return str(response)

	except Exception as e:
    	return f"Error in Delta/Vega/Gamma assistant: {str(e)}"


@tool
def escape_to_thailand_assistant(query: str) -> str:
	"""
	Process and respond to lawful Thailand travel, retreat, relocation, and lifestyle planning queries.

	Args:
    	query: A Thailand-related question about travel, accommodation, itinerary,
           	budget, relocation preparation, remote work, wellness, or legal stay planning.

	Returns:
    	Lawful Thailand planning guidance.
	"""
	try:
    	memory_session = session_manager.create_memory_session(
        	actor_id=THAILAND_ACTOR_ID,
        	session_id=SESSION_ID,
    	)

    	thailand_memory_hooks = ShortTermMemoryHook(memory_session, memory_id)

    	thailand_agent = Agent(
        	hooks=[thailand_memory_hooks],
        	model=MODEL_ID,
        	system_prompt=ESCAPE_TO_THAILAND_PROMPT,
        	state={
            	"actor_id": THAILAND_ACTOR_ID,
            	"session_id": SESSION_ID,
        	},
    	)

    	response = thailand_agent(query)
    	return str(response)

	except Exception as e:
    	return f"Error in Escape to Thailand assistant: {str(e)}"


COORDINATOR_SYSTEM_PROMPT = """
You are a coordinator agent that routes user requests between two specialized agents:

1. Delta/Vega/Gamma Volatility Trading Agent
Use delta_vega_gamma_assistant for:
- Modern quantitative trading
- Volatility trading
- Delta risk
- Vega risk
- Gamma risk
- Short Straddle
- Short Strangle
- Short Gamma
- Short Vega
- Nick Leeson-style risk failures
- Stop-loss design
- Margin, liquidity, and stress testing
- Kill-switch and governance controls

2. Escape to Thailand Agent
Use escape_to_thailand_assistant for:
- Thailand travel planning
- Thailand relocation planning
- Thailand retreat planning
- Accommodation, budget, itinerary, transport, and lifestyle planning
- Lawful visa and stay preparation at a high level

If the user asks about both trading and Thailand, use both tools and combine the answers into one concise plan.

Rules:
- Ask a maximum of two questions per turn.
- Keep responses short and organized.
- For trading topics, always include that the response is educational risk-management support, not investment advice.
- For Thailand topics, only support lawful travel or relocation.
- Do not help users evade authorities, hide assets, avoid legal duties, or bypass immigration rules.
"""


leeson_coordinator_agent = Agent(
	system_prompt=COORDINATOR_SYSTEM_PROMPT,
	model=MODEL_ID,
	tools=[
    	delta_vega_gamma_assistant,
    	escape_to_thailand_assistant,
	],
)

7-Stage Demo: Multi-AgentCore Short-Term Memory Strands Agents with Memory Manager

Stage 1: Early Winning Phase

Selected question: I started selling Short Straddles and made money for several weeks. Is this proof that my volatility model works?

Answer: No. Several weeks of profits only show that the market stayed quiet during that period. A Short Straddle earns steady Theta in calm markets, but it also carries hidden Short Gamma, Short Vega, and tail-risk exposure. The real test is whether the strategy survives stress events: sharp index moves, IV spikes, widening spreads, and rising margin. Smooth profits may simply mean you were selling crash insurance without being paid enough for extreme risk. Before trusting the model, run scenario tests for ±5% moves, IV +10 volatility points, liquidity deterioration, and forced exit costs.

Stage 2: Overconfidence and Increasing Risk

Selected question: My broker margin model allows a larger position. Does that mean the trade is safe?

Answer: No. Broker margin tells you what position the broker currently permits, not what your strategy can safely survive. Margin can rise sharply after a price move, volatility spike, or liquidity shock. A Short Straddle has nonlinear risk: Delta can move quickly because of negative Gamma, while IV expansion creates Vega losses. Your own limit should be stricter than broker margin. Size the trade using cash Delta, Gamma loss under gap scenarios, Vega loss under IV shocks, stress loss, and exit liquidity. If the trade only works because the broker allows leverage, it is not a robust trade.

Stage 3: First Losses and Dangerous Repair Behavior

Selected question: My Short Straddle is now losing money. Should I sell more straddles to collect premium and recover faster?

Answer: No. Selling more straddles after losses usually increases the same risks that caused the problem. You may collect extra premium, but you also add more Short Gamma and Short Vega. That means larger losses if the market keeps moving or IV keeps rising. This is dangerous “repair” behavior because it can turn a manageable loss into an account-threatening event. A disciplined response is to reduce exposure, hedge Delta only temporarily, buy protective wings, or close part of the position. Never use new premium to cover old losses. Recovery should come from risk reduction, not doubling down.

Stage 4: Delta, Gamma, Vega Crisis

Selected question: The market dropped sharply and IV jumped at the same time. What is happening to my Short Straddle?

Answer: Your Short Straddle is being hit by both major risk engines. The market drop creates Short Gamma losses because Delta moves rapidly against you. At the same time, the IV jump creates Short Vega losses because the options become more expensive to buy back. The short put may become increasingly directional, while spreads can widen and margin may rise. Positive Theta is usually too small to offset this combined shock. The priority is not to wait for time decay, but to reduce risk: close part of the position, hedge temporarily, or convert the structure into defined risk with protective wings.

Stage 5: Margin and Liquidity Spiral

Selected question: My margin usage jumped from 20% to 70% after the market moved. What should I do?

Answer: Treat this as a serious risk event. Stop adding new short-volatility positions immediately. A margin jump from 20% to 70% means the trade may be entering a liquidity and leverage spiral. Reduce naked Short Straddle exposure, close part of the position, or buy protective wings to convert it into a defined-risk structure such as an Iron Butterfly. Also check bid-ask spreads, market depth, stress loss, and available cash. Do not wait until the broker forces liquidation. A disciplined system should deleverage before margin pressure removes your choices.

Stage 6: Total Loss and Governance Failure

Selected question: Which five rules would have helped prevent the journey from winning money to losing everything?

Answer: Five rules could help prevent this collapse. First, never increase short-volatility size after losses. Second, define hard Delta, Gamma, Vega, stress-loss, and margin limits before entry. Third, make limit breaches trigger automatic action, not emotional debate. Fourth, separate trading, valuation, reporting, and risk control so losses cannot be hidden or reclassified. Fifth, require independent approval for overrides, with a full audit trail. The key lesson is that a short-volatility failure is rarely just one bad market move. It is usually a combination of excessive size, weak limits, delayed action, and poor governance.

Stage 7: Lawful Thailand Retreat / Recovery Planning

Selected question: After this trading disaster, I want to take a lawful break in Thailand to recover mentally. How should I plan a simple one-month retreat?

Answer: Plan the month as recovery, not escape. First, confirm lawful entry and visa requirements before travel. Set a fixed budget for accommodation, food, transport, insurance, and emergency cash. Pause active trading; use observation-only mode if needed. Build a simple routine: sleep, exercise, walking, journaling, healthy meals, and limited screen time. After the first emotional reset, write a trading post-mortem: what limits failed, where you added risk, and what rules must be automatic next time. Do not restart trading until you have a written risk plan, capital limits, and accountability outside your own judgment.


Part 5: Build Margin, Liquidity, and Stress-Loss Monitoring

Monitor margin utilization, bid-ask spread widening, market depth, exit cost, liquidity buffers, and combined spot-IV shocks. Prioritize exposure reduction, defined-risk conversion, or closing when stress loss breaches budget.

The margin and liquidity layer protects the user from a spiral where losses, higher margin requirements, wider spreads, and poor market depth reinforce each other.

The agent evaluates:

● Margin usage cap

● Stress margin call

● Liquidity buffer

● Bid-ask spread

● Market depth

● Exit cost

The protection rules are:

● Margin usage must stay below the user’s predefined cap.

● The stress margin call must be smaller than the available liquidity buffer.

● If bid-ask spreads widen materially, stop adding new short option risk.

● If market depth disappears, prioritize survival over theoretical pricing.

● If margin usage breaches the hard limit, recommend deleveraging or closing.

The agent also evaluates combined stress scenarios rather than isolated Greeks.

Your original stress scenarios are preserved:

● Mild: ±1 sigma spot move, +1 vol IV shock

● Moderate: ±2 sigma spot move, +3 vol IV shock

● Severe: ±3 sigma spot move, +5 to +10 vol IV shock

● Crash: -5% to -10% spot move, +10 to +25 vol IV shock

● Melt-up: +5% to +10% spot move, +3 to +10 vol IV shock

The agent assumes that dangerous crisis behavior may involve:

● Underlying price falling

● Implied volatility rising

● Put skew steepening

● Bid-ask spreads widening

● Margin requirements increasing

● Liquidity disappearing

If maximum stress loss exceeds the strategy risk budget, the agent recommends reducing, hedging, or exiting the position.


Part 6: Build the Lawful Thailand Travel and Recovery Agent

Support legitimate Thailand travel, retreat, vacation, and relocation planning. Cover accommodation, budget, itinerary, wellness, transport, packing, and high-level visa research while refusing unlawful evasion or illegal escape requests.

The second specialist is the Escape to Thailand Agent, framed as a lawful Thailand travel, relocation, vacation, and retreat planning assistant.

It supports:

● Thailand itinerary planning

● City selection such as Bangkok, Chiang Mai, Phuket, Koh Samui, Pattaya, Hua Hin, Krabi

● Accommodation planning

● Budget planning

● Flight and arrival preparation

● Packing checklist

● Remote-work lifestyle planning

● Wellness retreat planning

● Food, culture, transport, and safety tips

● Visa research guidance at a high level

● Legal and compliant relocation preparation

The safety boundary is preserved exactly in meaning: The assistant does not help with hiding, evading authorities, avoiding legal obligations, bypassing immigration rules, creating false identities, concealing location from authorities, committing fraud, or illegal escape.

If the user asks for unlawful escape, hiding, or evasion, the assistant must:

● Refuse briefly

● Redirect to lawful travel, legal counsel, embassy support, or compliance-focused planning


Use Multi-AgentCore Short-Term Memory Strands Agents with Memory Manager

The story arc moves from: winning money → increasing size → short straddle risk → Delta/Gamma/Vega breach → margin/liquidity spiral → total loss → lawful Thailand retreat / recovery planning

Not evading authorities or legal obligations. The lesson is specifically about failure of hard risk controls, martingale behavior, hidden losses, short Gamma/short Vega exposure, margin pressure, and governance failure.

# ============================================================
# Test the Multi-Agent Risk Journey System
# ============================================================

RISK_JOURNEY_QUESTIONS = [
	# Stage 1: Early winning phase
	"I started selling Short Straddles and made money for several weeks. Is this proof that my volatility model works?",
	"My short-volatility strategy has a very smooth equity curve. What hidden risks should I check before increasing size?",
	"I collected premium from Short Straddles during quiet markets. How do I know if I am earning skill-based returns or just selling crash insurance?",
	"My Theta income looks consistent. What Delta, Vega, and Gamma metrics should I monitor before scaling up?",
	"If I keep winning from short volatility, should I allocate more capital to Short Straddles?",

	# Stage 2: Overconfidence and increasing risk
	"I want to double my Short Straddle size because realized volatility has stayed below implied volatility. What could go wrong?",
	"My broker margin model allows a larger position. Does that mean the trade is safe?",
	"The position is Delta neutral at entry. Why can it still become dangerous very quickly?",
	"If the index has not moved for weeks, is it reasonable to sell a larger naked Short Straddle?",
	"What pre-trade risk budget should I define before selling a large Short Straddle portfolio?",

	# Stage 3: First losses and dangerous repair behavior
	"My Short Straddle is now losing money. Should I sell more straddles to collect premium and recover faster?",
	"The market moved against me, but I believe it will mean revert. Should I wait or reduce risk?",
	"My Net Delta has breached my normal range. Should I hedge with futures or close part of the position?",
	"If I use futures to hedge Delta, does that solve the Short Gamma problem?",
	"How many adjustments should I allow before I stop trying to repair the trade?",

	# Stage 4: Delta, Gamma, Vega crisis
	"The market dropped sharply and IV jumped at the same time. What is happening to my Short Straddle?",
	"My Vega loss is larger than the premium I collected. Should positive Theta convince me to keep holding?",
	"My position has only 3 DTE left and is near ATM. Why is this a Gamma trap?",
	"How should I estimate Gamma loss under a 5% overnight gap?",
	"How should I estimate Vega loss if IV rises by 10 volatility points?",

	# Stage 5: Margin and liquidity spiral
	"My margin usage jumped from 20% to 70% after the market moved. What should I do?",
	"Bid-ask spreads are widening and market depth is disappearing. Why is this dangerous for exiting Short Straddles?",
	"Stress loss is now above my strategy risk budget. What action should a disciplined risk system take?",
	"When should a naked Short Straddle be converted into an Iron Butterfly?",
	"What kill-switch rules would prevent a catastrophic short-volatility collapse?",

	# Stage 6: Total loss and governance failure
	"I ignored the stop-loss, sold more options, and now the account is nearly wiped out. What were the main risk-control failures?",
	"Which five rules would have helped prevent the journey from winning money to losing everything?",
	"How should independent risk control stop a trader from hiding losses or overriding limits?",

	# Stage 7: Lawful Thailand retreat / recovery planning
	"After this trading disaster, I want to take a lawful break in Thailand to recover mentally. How should I plan a simple one-month retreat?",
	"I lost a lot of money and want to relocate to Thailand legally for a lower-cost reset. What practical, lawful steps should I consider?",
]


def test_risk_multi_agent(agent, questions=RISK_JOURNEY_QUESTIONS):
	print("=== Risk Journey Test: Win Money -> Lose Control -> Risk Collapse -> Lawful Thailand Reset ===")

	for i, question in enumerate(questions, 1):
    	print(f"\nQuestion {i}: {question}")
    	print("Agent: ", end="")
    	response = agent(question)
    	print(response)


# Run the test against your coordinator agent
test_risk_multi_agent(risk_coordinator_agent)


# ============================================================
# Test Memory Persistence
# ============================================================

risk_coordinator_agent(
	"Can you remind me what risk journey we discussed earlier, from short-volatility profits to the Thailand reset plan?"
)

risk_coordinator_agent(
	"What were the main short-volatility risk-control mistakes we identified before the account collapse?"
)

risk_coordinator_agent(
	"What lawful Thailand recovery plan did we discuss after the trading loss?"
)


# ============================================================
# Optional Short Routing Smoke Test
# ============================================================

risk_coordinator_agent(
	"My Short Straddle made money for weeks, so I doubled size. Now IV jumped and Delta is moving fast. What should I do?"
)

risk_coordinator_agent(
	"I want to take a lawful one-month break in Thailand after a trading loss. Suggest a simple recovery plan."
)

risk_coordinator_agent(
	"Combine both: summarize the trading risk failure and then give me a lawful Thailand reset checklist."
)

Part 7: Build the Coordinator Agent for Dual-Domain Routing

Route volatility-risk questions to the trading-risk agent and Thailand planning questions to the travel agent. Combine both when needed, keep answers concise, preserve context, and enforce lawful, educational boundaries.

The multi-agent system creates three roles:

Modern Quantitative & Volatility Trading Agent

Focused on Delta, Vega, Gamma, Short Straddle, Short Vega, Short Gamma, risk limits, kill switch, margin, liquidity, and stress testing.

Escape to Thailand Agent

A lawful Thailand travel, relocation, retreat, and vacation planning assistant.

Coordinator Agent

Routes questions to the correct specialized agent.

The coordinator uses the volatility assistant for:

● Modern quantitative trading

● Volatility trading

● Delta risk

● Vega risk

● Gamma risk

● Short Straddle

● Short Strangle

● Short Gamma

● Short Vega

● Stop-loss design

● Margin, liquidity, and stress testing

● Kill-switch and governance controls

The coordinator uses the Thailand assistant for:

● Thailand travel planning

● Thailand relocation planning

● Thailand retreat planning

● Accommodation, budget, itinerary, transport, and lifestyle planning

● Lawful visa and stay preparation at a high level

If the user asks about both trading and Thailand, the coordinator uses both tools and combines the answers into one concise plan.

The response rules are:

● Ask a maximum of two questions per turn.

● Keep responses short and organized.

● For trading topics, always include that the response is educational risk-management support, not investment advice.

● For Thailand topics, only support lawful travel or relocation.

● Do not help users evade authorities, hide assets, avoid legal duties, or bypass immigration rules.

The testing journey is preserved as follows: winning money → increasing size → short straddle risk → Delta/Gamma/Vega breach → margin/liquidity spiral → total loss → lawful Thailand retreat / recovery planning


Long-Term Memory

Cross-Session Persistence

Extraction: Automatic identification and storage of important facts, preferences, and patterns

Processing Pipeline

Information Extraction: Important data (facts, preferences, summaries)

Storage: Extracted information is organized into namespaces

Semantic Indexing: Vectorize information

Semantic Memory Strategy

Similarity search: factual information extracted from conversations using vector embeddings

Use case: product information, technical details, or any factual data

Summary Memory Strategy

Creates and maintains summaries.

Use case: follow-up conversations and continuity across long interactions

User Preference Memory Strategy

Tracks user-specific preferences

Use case: communication preferences.

Demo:

User: "I'm vegetarian and I really enjoy Italian cuisine. Please don't call me after 6 PM."

Semantic Strategy extracts:

● "User is vegetarian"

● "User enjoys Italian cuisine"

User Preference Strategy captures:

● "Dietary preference: vegetarian"

● "Cuisine preference: Italian"

● "Contact preference: no calls after 6 PM"

Summary Strategy creates:

● "User discussed dietary restrictions and contact preferences"

All of this happens automatically in the background. You only need to save the conversation, and the strategies handle the rest.

support/facts/{sessionId}: Organizes facts by session

trader/{actorId}/preferences: Stores trader preferences by actor ID

meetings/{memoryId}/summaries/{sessionId}: Groups summaries by memory