# 風險評估

獲取 access token 所屬賬戶的風險評估檔案：最近一次測評的風險等級與得分、專業投資者（PI）狀態，以及 `approvals` 中各項的狀態。

以下欄位的取值由賬戶系統定義，而非本接口定義，接口原樣返回：

- `risk` 是最近一次測評的風險等級字串（例如 `A5`）。本接口不定義等級集合，也不定義等級之間的順序，請勿據此推斷風險承受能力的高低。
- `pi` 是專業投資者狀態碼。本接口不定義其取值含義，請當作不透明識別碼處理。
- `pi_end_at` 與 `deadlines` 是服務端返回的原始整數。本接口不定義其單位（秒或毫秒），將非 0 值轉換為時間之前請先確認單位。

`approvals` 與 `deadlines` 都以項為鍵。`approvals` 的值是字串而非布林值：`is_corporate_client` 返回 `"false"` / `"true"`，請比較字串，不要直接做真假判斷。

整數欄位可能以 JSON 字串返回（例如 `"pi_end_at": "0"`），這是網關按 proto3 JSON 序列化 int64 的方式。官方 SDK 兩種形式都能解析，並統一以整數暴露。

<CliCommand>
longbridge risk-assessment
</CliCommand>

## SDK Links

SDK 方法：`risk_assessment`

- Python: [longbridge.openapi.TradeContext.risk_assessment](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.TradeContext.risk_assessment)
- Rust: [longbridge::trade::TradeContext#risk_assessment](https://longbridge.github.io/openapi/rust/longbridge/trade/struct.TradeContext.html#method.risk_assessment)
- Go: [TradeContext.RiskAssessment](https://pkg.go.dev/github.com/longbridge/openapi-go/trade#TradeContext.RiskAssessment)
- Node.js: [TradeContext#riskAssessment](https://longbridge.github.io/openapi/nodejs/classes/TradeContext.html#riskassessment)
- Java: [TradeContext.getRiskAssessment](https://longbridge.github.io/openapi/java/com/longbridge/trade/TradeContext.html#getRiskAssessment())
- C++: [longbridge::trade::TradeContext::risk_assessment](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1trade_1_1_trade_context.html)

## Request

<table className="http-basic">
<tbody>
<tr><td className="http-basic-key">HTTP Method</td><td>GET</td></tr>
<tr><td className="http-basic-key">HTTP URL</td><td>/v1/members/me/risk-assessment </td></tr>
</tbody>
</table>

### Parameters

> Content-Type: application/json; charset=utf-8

該接口沒有請求參數，始終返回 access token 所屬賬戶的資料。

### Request Example

<Tabs groupId="request-example">
  <TabItem value="python" label="Python" default>

```python
from longbridge.openapi import TradeContext, Config, OAuthBuilder

oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.risk_assessment()
print(resp)
```

  </TabItem>
  <TabItem value="python-async" label="Python (async)">

```python
import asyncio
from longbridge.openapi import AsyncTradeContext, Config, OAuthBuilder

async def main() -> None:
    oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
    config = Config.from_oauth(oauth)
    ctx = AsyncTradeContext.create(config)
    resp = await ctx.risk_assessment()
    print(resp)

if __name__ == "__main__":
    asyncio.run(main())
```

  </TabItem>
  <TabItem value="nodejs" label="Node.js">

```javascript
const { Config, TradeContext, OAuth } = require('longbridge')

async function main() {
  const oauth = await OAuth.build('your-client-id', (_, url) => {
    console.log('Open this URL to authorize: ' + url)
  })
  const config = Config.fromOAuth(oauth)
  const ctx = TradeContext.new(config)
  const resp = await ctx.riskAssessment()
  console.log(resp)
}
main().catch(console.error)
```

  </TabItem>
  <TabItem value="java" label="Java">

```java
import com.longbridge.*;
import com.longbridge.trade.*;

class Main {
    public static void main(String[] args) throws Exception {
        try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
             Config config = Config.fromOAuth(oauth);
             TradeContext ctx = TradeContext.create(config)) {
            RiskAssessment resp = ctx.getRiskAssessment().get();
            System.out.println(resp);
        }
    }
}
```

  </TabItem>
  <TabItem value="rust" label="Rust">

```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::TradeContext, Config};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
    let config = Arc::new(Config::from_oauth(oauth));
    let (ctx, _) = TradeContext::new(config);
    let resp = ctx.risk_assessment().await?;
    println!("{:?}", resp);
    Ok(())
}
```

  </TabItem>
  <TabItem value="cpp" label="C++">

```cpp
#include <iostream>
#include <longbridge.hpp>

#ifdef WIN32
#include <windows.h>
#endif

using namespace longbridge;
using namespace longbridge::trade;

static void
run(const OAuth& oauth)
{
    Config config = Config::from_oauth(oauth);
    TradeContext ctx = TradeContext::create(config);

    ctx.risk_assessment([](auto res) {
        if (!res) { std::cout << "failed" << std::endl; return; }
        std::cout << "risk: " << res->risk << std::endl;
    });
}

int main(int argc, char const* argv[]) {
#ifdef WIN32
    SetConsoleOutputCP(CP_UTF8);
#endif

    const std::string client_id = "your-client-id";
    OAuthBuilder(client_id).build(
    [](const std::string& url) {
        std::cout << "Open this URL to authorize: " << url << std::endl;
    },
    [](auto res) {
        if (!res) {
            std::cout << "authorization failed: " << *res.status().message() << std::endl;
            return;
        }
        run(*res);
    });

    std::cin.get();
    return 0;
}
```

  </TabItem>
  <TabItem value="go" label="Go">

```go
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/longbridge/openapi-go/config"
	"github.com/longbridge/openapi-go/oauth"
	"github.com/longbridge/openapi-go/trade"
)

func main() {
	o := oauth.New("your-client-id").
		OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
	if err := o.Build(context.Background()); err != nil {
		log.Fatal(err)
	}
	conf, err := config.New(config.WithOAuthClient(o))
	if err != nil {
		log.Fatal(err)
	}
	tctx, err := trade.NewFromCfg(conf)
	if err != nil {
		log.Fatal(err)
	}
	defer tctx.Close()
	ra, err := tctx.RiskAssessment(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v\n", ra)
}
```

  </TabItem>
</Tabs>

## Response

### Response Headers

- Content-Type: application/json

### Response Example

```json
{
  "code": 0,
  "data": {
    "risk": "A5",
    "pi": 0,
    "approvals": {
      "car": "pass",
      "cka": "pass",
      "is_corporate_client": "false",
      "risk_audit": "pass"
    },
    "re_authentication": "",
    "pi_end_at": "0",
    "deadlines": {},
    "risk_assessment_at": "2026-10-14",
    "score": 0,
    "strategy_risk_levels": []
  }
}
```

### Response Status

| Status | Description | Schema                                            |
| ------ | ----------- | ------------------------------------------------- |
| 200    | 成功        | [risk_assessment_rsp](#schemarisk_assessment_rsp) |
| 400    | 內部錯誤    | None                                              |

## Schemas

### risk_assessment_rsp

<a id="schemarisk_assessment_rsp"></a>

| Name                 | Type     | Required | Description                                                                                                                       |
| -------------------- | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------- |
| risk                 | string   | 否       | 最近一次測評的風險等級，例如 `A5`。原樣返回；本接口不定義等級集合，也不定義等級之間的順序。可能為空。                              |
| pi                   | int32    | 否       | 專業投資者（PI）狀態碼，原樣返回。本接口不定義其取值含義。                                                                         |
| approvals            | object   | 否       | 各項的狀態，以項名為鍵、字串為值，例如 `car` / `cka` / `risk_audit` → `pass`。值是字串而非布林值：`is_corporate_client` 返回 `"false"` / `"true"`。 |
| re_authentication    | string   | 否       | 重新認證標記，原樣返回。可能為空。                                                                                             |
| pi_end_at            | int64    | 否       | 專業投資者狀態的結束時間，以原始整數返回，未設置時為 `0`。本接口不定義其單位（秒或毫秒）。可能以 JSON 字串返回。                   |
| deadlines            | object   | 否       | `deadlines` 中各項的值，以項名為鍵、整數為值。為原始整數，單位與 `pi_end_at` 一樣未被定義。                                          |
| risk_assessment_at   | string   | 否       | 服務端返回的最近一次評估日期，例如 `2026-10-14`。可能為空。                                                                        |
| score                | int32    | 否       | 測評得分                                                                                                                           |
| strategy_risk_levels | string[] | 否       | 賬戶的策略風險等級                                                                                                                 |