Skip to main content
Glama

flatten

Close all open trading positions to manage risk and exit the market. Returns a summary of closed positions for portfolio review.

Instructions

Immediately closes all open positions.

Returns:
    Summary of closed positions

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main handler function for the 'flatten' MCP tool. It closes all open positions by calling the broker's close_all_positions method and returns a formatted summary of the action or an error message.
    def flatten() -> str:
        """
        Immediately closes all open positions.
        
        Returns:
            Summary of closed positions
        """
        if broker is None:
            return "ERROR: Alpaca broker not initialized."
        
        try:
            result = broker.close_all_positions()
            
            if result['closed_count'] == 0:
                return "No positions to flatten."
            
            msg = [f"✅ Flattened {result['closed_count']} positions:"]
            for pos in result['positions_closed']:
                msg.append(f"  - {pos['symbol']}: {pos['qty']} shares ({pos['status']})")
            
            return "\n".join(msg)
        except Exception as e:
            logger.error(f"Flatten failed: {e}")
            return f"ERROR: Failed to flatten positions - {str(e)}"
  • server.py:375-378 (registration)
    Registration of the flatten tool as part of the Execution category tools in the MCP server using the register_tools function, which applies the @mcp.tool() decorator.
    register_tools(
        [place_order, cancel_order, get_positions, flatten, get_order_history],
        "Execution"
    )
  • The helper method in the AlpacaBroker class that performs the actual closing of all positions via the Alpaca trading client API. This is called by the flatten tool handler.
    def close_all_positions(self) -> Dict[str, Any]:
        """
        Close all open positions (emergency flatten).
        
        Returns:
            Dict with closed position count and details
        """
        try:
            closed = self.trading_client.close_all_positions(cancel_orders=True)
            logger.info(f"Closed {len(closed)} positions")
            
            return {
                "closed_count": len(closed),
                "positions_closed": [
                    {
                        "symbol": pos.symbol,
                        "qty": float(pos.qty) if pos.qty else 0,
                        "status": pos.status.value
                    }
                    for pos in closed
                ]
            }
        except Exception as e:
            logger.error(f"Failed to close all positions: {e}")
            raise
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries full burden. It states the action ('closes all open positions') and return value, but lacks critical behavioral details: whether this requires confirmation, its irreversible nature, potential market impact, rate limits, or error conditions. For a destructive operation with zero annotation coverage, this is a significant gap in disclosure.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is front-loaded with the core action in the first sentence and adds return information in a second sentence. Both sentences earn their place by providing essential operational and output details with zero waste or redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's high complexity (destructive financial operation) and lack of annotations, the description is minimally adequate. It covers purpose and output (aided by the output schema), but fails to address critical behavioral aspects like safety warnings or prerequisites. With no annotations and an output schema, it meets baseline but leaves gaps for a high-stakes tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has 0 parameters with 100% schema description coverage, so no parameter documentation is needed. The description does not mention parameters, which is appropriate. Baseline is 4 for zero parameters, as it avoids unnecessary detail.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Immediately closes all open positions') and distinguishes it from siblings like 'cancel_order' (which cancels specific orders) or 'get_positions' (which retrieves position data). The verb 'closes' and resource 'all open positions' are precise and unambiguous.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context ('Immediately closes all open positions'), suggesting this tool is for risk management or liquidation scenarios. However, it does not explicitly state when to use it versus alternatives like 'cancel_order' for specific orders or provide exclusions (e.g., not for partial closures). The guidance is clear but lacks explicit sibling differentiation.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/N-lia/MonteWalk'

If you have feedback or need assistance with the MCP directory API, please join our Discord server