tt-brokerage-interface
A robust interface for interacting with TastyTrade financial brokerage accounts, facilitating portfolio oversight, position analysis, and trade execution within the TastyTrade ecosystem.
Author

ferdousbhai
Quick Info
Actions
Tags
tt-brokerage-interface: TastyTrade Protocol Engine
This Model Context Protocol (MCP) server acts as a gateway to TastyTrade brokerage services. It empowers Large Language Models (LLMs) to query account status, evaluate holdings, and submit transactional instructions. Key capabilities include AI-driven trade concept generation, automated volatility metric evaluation prompts, and integrated velocity capping (set at 2 actions per second) to ensure API stability.
Credential Acquisition
OAuth Configuration Procedure: 1. Establish an OAuth application at: https://my.tastytrade.com/app.html#/manage/api-access/oauth-applications 2. Ensure all permissions scopes are selected; retain the generated client identifier and secret key. 3. Within your OAuth application settings, initiate a "New Personal OAuth Grant" (confirming all scope selections). 4. Capture the resultant refresh token. 5. Configure the MCP service runtime with these parameters (refer to the 'Deployment' section).
Available MCP Operations
Account Oversight & Holdings
get_balances()- Retrieves current account equity and available margin/buying power.get_positions()- Fetches details for all currently held assets.get_net_liquidating_value_history(time_back='1y')- Historical tracking of portfolio valuation ('1d', '1m', '3m', '6m', '1y', 'all' intervals supported).get_transaction_history(days=90, underlying_symbol=None, transaction_type=None)- Logs all historical financial events (trades and cash movements; defaults to the preceding 90 days; filterable by 'Trade' or 'Money Movement').get_order_history(days=7, underlying_symbol=None)- Review of placed orders, including fulfilled, withdrawn, and rejected requests (default lookback is 7 days).
Market Intelligence & Data Retrieval
get_quotes(instruments, timeout=10.0)- Provides immediate pricing data for numerous securities/options via DXLink streaming feeds.get_greeks(options, timeout=10.0)- Calculates option sensitivities (Delta, Gamma, Theta, Vega, Rho) through DXLink streaming.get_market_metrics(symbols)- Yields metrics like Implied Volatility Rank/Percentile, Beta, and liquidity indicators for specified tickers.market_status(exchanges=['Equity'])- Reports the operational schedule and current state for designated exchanges ('Equity', 'CME', 'CFE', 'Smalls').search_symbols(symbol)- Queries the system for matching security identifiers based on name or ticker.get_current_time_nyc()- Returns the current timestamp corresponding to New York market time.
Transactional Control
get_live_orders()- Lists all pending order submissions.place_order(legs, price=None, time_in_force='Day', dry_run=False)- Submits complex, multi-component orders, automatically deriving suggested pricing from live quotes if the price parameter is omitted.- Equity Actions: 'Buy', 'Sell'
- Option Actions: 'Buy to Open', 'Buy to Close', 'Sell to Open', 'Sell to Close'
replace_order(order_id, price)- Adjusts the limit price of an existing order (for structural changes, a cancel/replace sequence is recommended).delete_order(order_id)- Terminates a specific order by its unique identifier.
User Watchlist Management
get_watchlists(watchlist_type='private', name=None)- Access user watchlists ('public' or 'private'; retrieves all if 'name' is null).manage_private_watchlist(action, symbols, name='main')- Adds or removes security lists from designated private collections.delete_private_watchlist(name)- Erases a user-defined private watchlist.
AI Analytical Functions
generate_trade_ideas(focus_symbols=None, risk_tolerance='moderate', max_ideas=5)- Leverages artificial intelligence to formulate concrete, executable trade proposals based on current holdings, market data, volatility profiles, and watchlists.
Predefined MCP Directives
- IV Rank Analysis Prompt - A built-in command sequence designed to scrutinize IV rank extremes across the user's portfolio and tracked symbols to pinpoint optimal entry or exit points.
Core Capabilities
Intelligent Order Submission
- Automatic quotation sourcing to determine appropriate pricing when a specific price point is not mandated.
- Unified handling for complex options structures (e.g., vertical spreads, iron condors) within a single invocation.
- Safety validation via a simulation ('dry-run') mode prior to live submission.
Integrated AI Trading Assistant
- Idea Synthesis: Employs machine learning to analyze account state, market conditions, and volatility to produce specific, actionable investment suggestions.
- Volatility Triggers: Offers specialized prompts for identifying when Implied Volatility suggests favorable pricing conditions.
- Risk Profiling: Provides suggestions calibrated against user-defined risk appetites (conservative, moderate, aggressive).
Resiliency and Throttling
- Internal mechanism limits operational throughput to 2 queries per second, mitigating risk of API service interruption.
- Robust error interception and detailed logging mechanisms.
MCP Client Configuration Reference
Incorporate the following structure into your MCP client manifest (e.g., claude_desktop_config.json):
{
"mcpServers": {
"tt_brokerage": {
"command": "uvx",
"args": ["tasty-agent"],
"env": {
"TASTYTRADE_CLIENT_SECRET": "your_client_secret",
"TASTYTRADE_REFRESH_TOKEN": "your_refresh_token",
"TASTYTRADE_ACCOUNT_ID": "your_account_id"
}
}
},
"capabilities": {
"sampling": {}
}
}
Note: Enabling the sampling capability is necessary for activating advanced, AI-driven trade analysis features. Currently functional within VS Code environments; support in Claude Desktop is forthcoming.
Usage Illustrations
"Display my current account ledger and open positions"
"Fetch current market pricing for SPY and AAPL instruments"
"Query the quote for TQQQ call option, strike 100, expiration 2026-01-16"
"Retrieve Greeks for AAPL put option, strike 150, expiration 2024-12-20"
"Initiate purchase of 100 shares of AAPL" (auto-price determined)
"Submit order: buy 100 AAPL shares at $150.00"
"Place order: Buy to open 17 TQQQ calls, strike 100, maturing 2026-01-16"
"Execute a vertical spread trade: buy to open AAPL 150 Call and sell to open AAPL 155 Call, both expiring 2024-12-20"
"Liquidate my AAPL holding: Sell to close 10 AAPL call contracts"
"Adjust order ID 12345 to a limit price of $10.05"
"Cancel the submission identified by ID 12345"
"Review my trading activity since the start of this year"
"List all my privately managed asset lists"
"Incorporate TSLA and NVDA into my 'tech_tracking' list"
"Remove AAPL from the 'tech_tracking' watchlist"
"Request AI-generated trade concepts for my current assets"
"Generate high-risk trade recommendations focused on AAPL and TSLA"
Background Execution Framework
Execute recurring, automated trading routines:
# Single execution based on instruction set
uv run background.py "Review account health and execute necessary rebalancing moves"
# Automated hourly execution
uv run background.py "Continuously check SPY for notable movements and issue alerts" --hourly
# Automated daily execution
uv run background.py "Produce a comprehensive end-of-day portfolio synopsis" --daily
# Custom interval (seconds)
uv run background.py "Scan for premium selling opportunities" --period 1800 # Every half hour
# Specific scheduled start time (NYC focus)
uv run background.py "Execute pre-market setup routine" --schedule "9:30am" --hourly
# Market open trigger shorthand (9:30 AM EST)
uv run background.py "Run systematic 'buy-the-dip' logic" --market-open --hourly
Development & Debugging
Interactive Testing with chat.py
For iterative testing during development, ensure environment variables are set in a .env file:
TASTYTRADE_CLIENT_SECRET=your_secret
TASTYTRADE_REFRESH_TOKEN=your_token
TASTYTRADE_ACCOUNT_ID=your_account_id (defaults to the primary account)
# Optional: Define AI provider/model for idea generation
# OPENAI_API_KEY=your_openai_key
# MODEL_IDENTIFIER=provider:model_name (defaults to openai:gpt-5-mini)
Launch the interactive client session:
uv run chat.py
Example interactions: - "What are my account holdings?" - "Fetch the price data for SPY" - "Simulate order placement: buy 100 shares of AAPL at $150 using dry-run"
Debugging via MCP Inspector
Utilize the protocol inspection tool for real-time request/response monitoring:
npx @modelcontextprotocol/inspector uvx tasty-agent
Licensing
MIT License.
Conceptual Context: XMLHttpRequest (XHR) serves as a foundational JavaScript API object enabling asynchronous HTTP communication between a web client and a remote server after the initial page load. This mechanism is central to Ajax programming paradigms, moving beyond traditional page reloads for data interaction.
== Historical Development ==
The conceptual basis for XHR originated around 2000 within the Microsoft Outlook development team. Its initial implementation appeared in Internet Explorer 5 (1999), though it utilized COM object identifiers like ActiveXObject("Msxml2.XMLHTTP"). By the release of Internet Explorer 7 (2006), native support for the standardized XMLHttpRequest identifier became universal across major browsers, including Mozilla's Gecko (2002), Safari 1.2 (2004), and Opera 8.0 (2005).
=== Standardization Trajectory === The W3C formalized the specification via a Working Draft on April 5, 2006. Level 2 specifications, introduced February 25, 2008, augmented the original with features like event progress monitoring, cross-site request facilitation, and binary stream handling. Later, in 2011, Level 2 features were integrated back into the primary specification. Development responsibility transitioned to WHATWG in late 2012, which now maintains the living document using Web IDL definitions.
== Typical Implementation Flow == The process of issuing a request using XHR generally follows distinct programming stages:
- Instantiation: Create an
XMLHttpRequestinstance via its constructor. - Configuration: Invoke the
open()method to define the request method (GET/POST, etc.), specify the target URI, and select synchronous or asynchronous execution. - Asynchronous Listener Setup: For non-blocking operations, attach an event handler to track state changes.
- Transmission: Start the communication by calling the
send()method, optionally including payload data. - Response Handling: Monitor the event listener. Upon receiving data, it populates properties like
responseText. Completion is signaled when the object transitions to state 4 ("done").
Beyond these core steps, XHR offers extensive control, such as injecting custom HTTP headers, uploading complex data via the send() argument, parsing responses as JSON directly into native objects, or processing streamed data incrementally. Requests can also be externally terminated or subjected to time-out constraints.
== Inter-Domain Communication == *In the nascent stages of the World Wide Web, restrictions were observed preventing direct interaction betw
