Skip to main content
Glama
laukikk

Alpaca Trading MCP Server

by laukikk

place_market_order

Execute immediate stock trades at current market prices to buy or sell shares. Specify symbol, quantity, and side (buy/sell) for order confirmation.

Instructions

Place a market order to buy or sell a stock.

Args: symbol: Stock symbol (e.g., 'AAPL') quantity: Number of shares to buy or sell (can be fractional) side: Either 'buy' or 'sell'

Returns: Order confirmation details

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolYes
quantityYes
sideYes

Implementation Reference

  • Core handler for the 'place_market_order' tool. Validates input parameters, constructs an AlpacaOrderRequest for a MARKET order, submits it using the helper function calls.place_order, and formats the response with order details.
    @mcp.tool()
    def place_market_order(symbol: str, quantity: float, side: str) -> str:
        """
        Place a market order to buy or sell a stock.
        
        Args:
            symbol: Stock symbol (e.g., 'AAPL')
            quantity: Number of shares to buy or sell (can be fractional)
            side: Either 'buy' or 'sell'
        
        Returns:
            Order confirmation details
        """
        # Validate side
        try:
            order_side = AlpacaOrderSide(side.lower())
        except ValueError:
            return f"Invalid side: {side}. Must be 'buy' or 'sell'."
        
        # Create order request
        order_request = AlpacaOrderRequest(
            symbol=symbol,
            qty=float(quantity),
            side=order_side,
            type=AlpacaOrderType.MARKET,
            time_in_force=AlpacaTimeInForce.DAY
        )
        
        try:
            order = calls.place_order(trading_client, order_request)
            
            return (
                f"Market 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"Status: {order.status.value}\n"
                f"Created At: {order.created_at}\n"
            )
        except Exception as e:
            return f"Error placing market order: {str(e)}"
  • Helper function that handles order submission to Alpaca API. Converts custom AlpacaOrderRequest model to Alpaca-native request objects based on order type and submits the order.
    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__)
  • Pydantic model defining the structure for order requests, used internally by the tool handler to create market orders. Includes type definitions for side, type, etc.
    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
  • Enum defining valid order sides ('buy', 'sell'), used for input validation in the tool.
    class AlpacaOrderSide(str, Enum):
        BUY = 'buy'
        SELL = 'sell'

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