Skip to main content
Glama
laukikk

Alpaca Trading MCP Server

by laukikk

place_limit_order

Execute buy or sell orders for stocks at specific prices using limit orders to control trade execution costs.

Instructions

Place a limit order to buy or sell a stock at a specified price.

Args: symbol: Stock symbol (e.g., 'AAPL') quantity: Number of shares to buy or sell (can be fractional) side: Either 'buy' or 'sell' limit_price: Maximum price for buy or minimum price for sell time_in_force: Order duration - 'day', 'gtc' (good till canceled), 'ioc' (immediate or cancel)

Returns: Order confirmation details

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolYes
quantityYes
sideYes
limit_priceYes
time_in_forceNoday

Implementation Reference

  • The primary handler function for the 'place_limit_order' tool. It validates input parameters, constructs an AlpacaOrderRequest with LIMIT order type, calls the place_order helper, and returns order confirmation details.
    @mcp.tool()
    def place_limit_order(
        symbol: str, 
        quantity: float, 
        side: str, 
        limit_price: float, 
        time_in_force: str = "day"
    ) -> str:
        """
        Place a limit order to buy or sell a stock at a specified price.
        
        Args:
            symbol: Stock symbol (e.g., 'AAPL')
            quantity: Number of shares to buy or sell (can be fractional)
            side: Either 'buy' or 'sell'
            limit_price: Maximum price for buy or minimum price for sell
            time_in_force: Order duration - 'day', 'gtc' (good till canceled), 'ioc' (immediate or cancel)
        
        Returns:
            Order confirmation details
        """
        # Validate side
        try:
            order_side = AlpacaOrderSide(side.lower())
        except ValueError:
            return f"Invalid side: {side}. Must be 'buy' or 'sell'."
        
        # Validate time in force
        try:
            order_tif = AlpacaTimeInForce(time_in_force.lower())
        except ValueError:
            return f"Invalid time in force: {time_in_force}. Valid options are: day, gtc, ioc, fok"
        
        # Create order request
        order_request = AlpacaOrderRequest(
            symbol=symbol,
            qty=float(quantity),
            side=order_side,
            type=AlpacaOrderType.LIMIT,
            time_in_force=order_tif,
            limit_price=float(limit_price)
        )
        
        try:
            order = calls.place_order(trading_client, order_request)
            
            return (
                f"Limit order placed successfully!\n\n"
                f"Order ID: {order.id}\n"
                f"Symbol: {order.symbol}\n"
                f"Side: {order.side.value}\n"
                f"Type: {order.type.value}\n"
                f"Quantity: {order.qty}\n"
                f"Limit Price: ${order.limit_price:.2f}\n"
                f"Time in Force: {order.time_in_force.value}\n"
                f"Status: {order.status.value}\n"
                f"Created At: {order.created_at}\n"
            )
        except Exception as e:
            return f"Error placing limit order: {str(e)}"
  • Pydantic model defining the structure and validation for order requests, including fields used by place_limit_order such as symbol, qty, side, type=LIMIT, time_in_force, and limit_price.
    class AlpacaOrderRequest(BaseModel):
        symbol: str
        qty: Union[int, float]
        side: AlpacaOrderSide
        type: AlpacaOrderType
        time_in_force: AlpacaTimeInForce
        limit_price: Optional[float] = None
        stop_price: Optional[float] = None
        client_order_id: Optional[str] = None
        extended_hours: Optional[bool] = False
  • Helper function that translates the AlpacaOrderRequest into the appropriate Alpaca SDK order request (LimitOrderRequest for LIMIT type) and submits it to the trading client.
    def place_order(client: TradingClient, order_details: AlpacaOrderRequest):
        """
        Place an order with flexible order types
        
        :param client: Alpaca trading client
        :param order_details: Order request details
        :return: Placed AlpacaOrder
        """
        # Map Pydantic model to Alpaca order request based on order type
        if order_details.type == AlpacaOrderType.MARKET:
            order_request = MarketOrderRequest(
                symbol=order_details.symbol,
                qty=order_details.qty,
                side=order_details.side,
                time_in_force=order_details.time_in_force
            )
        elif order_details.type == AlpacaOrderType.LIMIT:
            if not order_details.limit_price:
                raise ValueError("Limit price is required for limit orders")
            order_request = LimitOrderRequest(
                symbol=order_details.symbol,
                qty=order_details.qty,
                side=order_details.side,
                time_in_force=order_details.time_in_force,
                limit_price=order_details.limit_price
            )
        elif order_details.type == AlpacaOrderType.STOP:
            if not order_details.stop_price:
                raise ValueError("Stop price is required for stop orders")
            order_request = StopOrderRequest(
                symbol=order_details.symbol,
                qty=order_details.qty,
                side=order_details.side,
                time_in_force=order_details.time_in_force,
                stop_price=order_details.stop_price
            )
        elif order_details.type == AlpacaOrderType.STOP_LIMIT:
            if not (order_details.stop_price and order_details.limit_price):
                raise ValueError("Both stop and limit prices are required for stop-limit orders")
            order_request = StopLimitOrderRequest(
                symbol=order_details.symbol,
                qty=order_details.qty,
                side=order_details.side,
                time_in_force=order_details.time_in_force,
                stop_price=order_details.stop_price,
                limit_price=order_details.limit_price
            )
        else:
            raise ValueError(f"Unsupported order type: {order_details.type}")
    
        # Submit order
        order = client.submit_order(order_request)
        return AlpacaOrder(**order.__dict__)
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. While it implies a write operation ('Place'), it doesn't mention critical aspects like authentication requirements, rate limits, execution guarantees, or potential side effects (e.g., funds reservation). This is inadequate for a financial transaction tool.

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

Conciseness4/5

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

The description is well-structured with clear sections (Args, Returns) and uses bullet-like formatting. Every sentence adds value, though the 'Returns' section could be more specific. It's appropriately sized for a 5-parameter tool without unnecessary elaboration.

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

Completeness2/5

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

For a financial order placement tool with no annotations and no output schema, the description is incomplete. It lacks critical context about authentication, error conditions, order status tracking, and what 'Order confirmation details' actually contains. The agent would need to guess important behavioral aspects.

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

Parameters5/5

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

Given 0% schema description coverage, the description fully compensates by explaining all 5 parameters with clear semantics. It defines each parameter's purpose, provides examples (e.g., 'AAPL'), clarifies numeric types (e.g., 'can be fractional'), enumerates valid values (e.g., 'buy' or 'sell'), and explains constraints (e.g., 'Maximum price for buy').

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 ('Place a limit order') and resource ('stock'), distinguishing it from sibling tools like place_market_order or place_stop_order. It precisely defines the tool's function without being tautological.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives like place_market_order or place_stop_limit_order. It lacks context about appropriate scenarios, prerequisites, or exclusions, leaving the agent to infer usage from the tool name alone.

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/laukikk/alpaca-mcp'

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