Skip to main content
Glama
aahl

OKX MCP Server

by aahl

Get account positions

account_positions

Retrieve current trading positions from your OKX account, displaying net positions or long/short positions based on your account mode, sorted by creation time.

Instructions

Retrieve information on your OKX positions. When the account is in net mode, net positions will be displayed, and when the account is in long/short mode, long or short positions will be displayed. Return in reverse chronological order using ctime.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
instTypeNoInstrument type: `SPOT`: 币币现货/`MARGIN`: 币币杠杆/`SWAP`: 永续合约/`FUTURES`: 交割合约/`OPTION`: 期权.`instId` will be checked against `instType` when both parameters are passed. Optional, all by default if not passed
instIdNoInstrument ID, e.g. `BTC-USDT-SWAP`. Single instrument ID or multiple instrument IDs (no more than 10) separated with comma. Optional, all by default if not passed
posIdNoSingle position ID or multiple position IDs (no more than 20) separated with comma. There is attribute expiration, the posId and position information will be cleared if it is more than 30 days after the last full close position. Optional, all by default if not passed

Implementation Reference

  • The @mcp.tool decorator defines and registers the 'account_positions' tool, including input schema via Pydantic Fields and the handler function logic that calls the OKX API to fetch positions and attaches a detailed response schema.
    @mcp.tool(
        title="Get account positions",
        description="Retrieve information on your OKX positions. When the account is in net mode, net positions will be displayed, "
                    "and when the account is in long/short mode, long or short positions will be displayed. "
                    "Return in reverse chronological order using ctime.",
    )
    def account_positions(
        instType: str = Field("", description="Instrument type: "
                                              "`SPOT`: 币币现货/"
                                              "`MARGIN`: 币币杠杆/"
                                              "`SWAP`: 永续合约/"
                                              "`FUTURES`: 交割合约/"
                                              "`OPTION`: 期权."
                                              "`instId` will be checked against `instType` when both parameters are passed. "
                                              "Optional, all by default if not passed"),
        instId: str = Field("", description="Instrument ID, e.g. `BTC-USDT-SWAP`. Single instrument ID or multiple instrument IDs (no more than 10) separated with comma. "
                                            "Optional, all by default if not passed"),
        posId: str = Field("", description="Single position ID or multiple position IDs (no more than 20) separated with comma. "
                                           "There is attribute expiration, the posId and position information will be cleared if it is more than 30 days after the last full close position. "
                                           "Optional, all by default if not passed"),
    ):
        if str(instType).upper() in ["SPOT"]:
            instType = ""
        resp = ACCOUNT.get_positions(instType, instId=instId, posId=posId) or {}
        if int(resp.get("code", 0)):
            return resp
        resp["_response_schema"] = """
        mgnMode: Margin mode
        posSide: Position side. long, pos is positive; short, pos is positive;
                 net (FUTURES/SWAP/OPTION: positive pos means long position and negative pos means short position. For MARGIN, 
                 pos is always positive, posCcy being base currency means long position, posCcy being quote currency means short position.)
        pos: Quantity of positions. In the isolated margin mode, when doing manual transfers, a position with pos of 0 will be generated after the deposit is transferred
        posCcy: Position currency, only applicable to MARGIN positions.
        availPos: Position that can be closed. Only applicable to MARGIN and OPTION. 
                  For MARGIN position, the rest of sz will be SPOT trading after the liability is repaid while closing the position. 
                  Please get the available reduce-only amount from `Get maximum available tradable amount` if you want to reduce the amount of SPOT trading as much as possible
        avgPx: Average open price. Under cross-margin mode, the entry price of expiry futures will update at settlement to the last settlement price, and when the position is opened or increased
        nonSettleAvgPx: Non-settlement entry price. The non-settlement entry price only reflects the average price at which the position is opened or increased. Applicable to cross FUTURES positions
        markPx: Latest Mark price
        upl: Unrealized profit and loss calculated by mark price
        uplRatio: Unrealized profit and loss ratio calculated by mark price
        uplLastPx: Unrealized profit and loss calculated by last price. Main usage is showing, actual value is upl
        uplRatioLastPx: Unrealized profit and loss ratio calculated by last price
        lever: Leverage. Not applicable to OPTION and positions of cross margin mode under Portfolio margin
        liqPx: Estimated liquidation price. Not applicable to OPTION
        imr: Initial margin requirement
        margin: Margin, can be added or reduced
        mgnRatio: Maintenance margin ratio
        mmr: Maintenance margin requirement
        liab: Liabilities, only applicable to MARGIN
        liabCcy: Liabilities currency
        optVal: Option Value, only applicable to OPTION
        pendingCloseOrdLiabVal: The amount of close orders of isolated margin liability
        notionalUsd: Notional value of positions in USD
        adl: Auto-deleveraging (ADL) indicator. Divided into 6 levels, from 0 to 5, the smaller the number, 
             the weaker the adl intensity. Only applicable to FUTURES/SWAP/OPTION
        ccy: Currency used for margin
        last: Latest traded price
        idxPx: Latest underlying index price
        usdPx: Latest USD price of the ccy on the market, only applicable to FUTURES/SWAP/OPTION
        bePx: Breakeven price
        deltaBS: delta: Black-Scholes Greeks in dollars, only applicable to OPTION
        deltaPA: delta: Greeks in coins, only applicable to OPTION
        gammaBS: gamma: Black-Scholes Greeks in dollars, only applicable to OPTION
        gammaPA: gamma: Greeks in coins, only applicable to OPTION
        thetaBS: theta:Black-Scholes Greeks in dollars, only applicable to OPTION
        thetaPA: theta:Greeks in coins, only applicable to OPTION
        vegaBS: vega:Black-Scholes Greeks in dollars, only applicable to OPTION
        vegaPA: vega:Greeks in coins, only applicable to OPTION
        spotInUseAmt: Spot in use amount. Applicable to Portfolio margin
        spotInUseCcy: Spot in use unit, e.g. BTC. Applicable to Portfolio margin
        clSpotInUseAmt: User-defined spot risk offset amount. Applicable to Portfolio margin
        maxSpotInUseAmt: Max possible spot risk offset amount. Applicable to Portfolio margin
        bizRefId: External business id, e.g. experience coupon id
        bizRefType: External business type
        realizedPnl: Realized profit and loss. Only applicable to FUTURES/SWAP/OPTION. 
                     realizedPnl=pnl+fee+fundingFee+liqPenalty+settledPnl
        settledPnl: Accumulated settled profit and loss (calculated by settlement price). Only applicable to cross FUTURES
        pnl: Accumulated pnl of closing order(s) (excluding the fee)
        fee: Accumulated fee. Negative number represents the user transaction fee charged by the platform.Positive number represents rebate.
        fundingFee: Accumulated funding fee
        liqPenalty: Accumulated liquidation penalty. It is negative when there is a value
        closeOrderAlgo: Close position algo orders attached to the position. 
                        This array will have values only after you request 'Place algo order' with closeFraction=1
        closeOrderAlgo.slTriggerPx: Stop-loss trigger price
        closeOrderAlgo.tpTriggerPx: Take-profit trigger price
        closeOrderAlgo.slTriggerPxType: Stop-loss trigger price type.
            last: last price
            index: index price
            mark: mark price
        closeOrderAlgo.tpTriggerPxType: Take-profit trigger price type.
            last: last price
            index: index price
            mark: mark price
        closeOrderAlgo.closeFraction: Fraction of position to be closed when the algo order is triggered
        """
        return resp
  • Top-level registration call that invokes add_tools from the account module to register all account-related tools, including 'account_positions', to the FastMCP instance.
    account.add_tools(mcp)
  • Initialization of the OKX AccountAPI client instance used by the account_positions handler and other account tools.
    ACCOUNT = AccountAPI(
        api_key=OKX_API_KEY,
        api_secret_key=OKX_API_SECRET,
        passphrase=OKX_PASSPHRASE,
        flag=OKX_TRADE_FLAG,
        domain=OKX_BASE_URL,
    )
Behavior3/5

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

No annotations are provided, so the description carries the full burden. It discloses behavioral traits: it returns positions based on account mode (net or long/short) and orders them in reverse chronological order by ctime. However, it doesn't cover critical aspects like authentication needs, rate limits, error conditions, or response format, which are significant gaps for a tool with no annotation coverage.

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 appropriately sized and front-loaded: the first sentence states the core purpose, followed by clarifying details about account modes and ordering. Every sentence earns its place by adding context without redundancy, making it efficient and easy to parse.

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 no annotations and no output schema, the description provides basic purpose and behavioral context (account modes, ordering) but lacks completeness. It doesn't explain the return values, error handling, or security requirements, which are important for a tool that retrieves financial data. The schema covers parameters well, but overall context is minimal for a tool with potential complexity.

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

Parameters3/5

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

Schema description coverage is 100%, so the schema fully documents the three optional parameters (instType, instId, posId) with their types, defaults, and descriptions. The description adds no parameter-specific information beyond what's in the schema, such as how filtering works or interactions between parameters. Baseline 3 is appropriate when the schema does the heavy lifting.

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

Purpose4/5

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

The description clearly states the verb ('retrieve') and resource ('account positions'), specifying it's for OKX positions. It distinguishes from siblings like account_balance (which retrieves balance, not positions) and account_position_risk (which likely focuses on risk metrics). However, it doesn't explicitly differentiate from close_positions or other position-related tools beyond the retrieval action.

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

Usage Guidelines3/5

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

The description implies usage by mentioning net vs. long/short mode contexts, but doesn't explicitly state when to use this tool versus alternatives like account_position_risk or close_positions. No exclusions or prerequisites are provided, leaving the agent to infer based on the retrieval purpose versus mutation/analysis tools in the sibling list.

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/aahl/mcp-okx'

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