Skip to main content
Glama
aahl

OKX MCP Server

by aahl

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,
    )

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