close_position
Close open trading positions on Hyperliquid exchange using market or limit orders to manage risk and exit trades.
Instructions
Close an open position (market close or limit close)
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| symbol | Yes | Market symbol | |
| price | No | Limit price to close at (omit for market close) |
Implementation Reference
- src/hyperliquid_mcp/client.py:172-192 (handler)Main handler function that executes the close_position logic. Gets open positions, validates the symbol exists, determines position side (long/short), calculates appropriate price if market close, and submits a reduce-only order to close the position.
def close_position(self, symbol: str, price: Optional[float] = None) -> dict[str, Any]: """Close an open position.""" exchange = self._require_exchange() positions = self.get_positions() pos = next((p for p in positions if p["symbol"].upper() == symbol.upper()), None) if not pos: raise ValueError(f"No open position for {symbol}.") size = abs(float(pos["size"])) is_long = float(pos["size"]) > 0 # To close: sell if long, buy if short is_buy = not is_long if price is None: # Market close info = self.get_market_info(symbol) mid = float(info["mid_price"]) price = round(mid * (1.01 if is_buy else 0.99), 6) result = exchange.order(symbol.upper(), is_buy, size, price, {"limit": {"tif": "Gtc"}}, reduce_only=True) return {"status": "close_submitted", "symbol": symbol, "size": size, "result": result} - Input schema definition for the close_position tool. Defines the expected parameters: symbol (required string) and price (optional number for limit closes).
Tool( name="close_position", description="Close an open position (market close or limit close)", inputSchema={ "type": "object", "properties": { "symbol": {"type": "string", "description": "Market symbol"}, "price": {"type": "number", "description": "Limit price to close at (omit for market close)"}, }, "required": ["symbol"], }, ), - src/hyperliquid_mcp/server.py:158-159 (registration)Dispatch case in the _dispatch function that routes close_position tool calls to the client.close_position method with symbol and optional price arguments.
case "close_position": return client.close_position(args["symbol"], args.get("price"))