PiTrade Client APIs Authentication

PiTrade Native APIs use a two-step authentication process. First, you generate a JWT token using your credentials, then exchange it for an access token that is used to authenticate all API requests.

Authentication Flow Overview

The authentication process consists of three main steps:

  1. Generate JWT Token - Create a signed JWT using your clientId and apiKey
  2. Exchange for Access Token - Call /auth/token with your JWT to receive tokens
  3. Use IdToken - Include the IdToken in the Authorization header for all Native API requests

Step 1: Generate JWT Token

Create a JWT payload with your client credentials:

JWT Payload Structure

{
  "clientId": "YOUR_CLIENT_ID",
  "iat": 1689000000,
  "exp": 1689003600
}

JWT Payload Parameters

ParameterTypeRequiredDescription
clientIdstringYesYour PiTrade API client ID provided by PiTrade
iatintegerYesIssued at time (Unix timestamp) - time when the token was created
expintegerYesExpiration time (Unix timestamp) - typically 1 hour after iat

JWT Generation

Create a JWT by:

  1. Encoding the payload as JSON
  2. Signing with your apiKey using HMAC-SHA256
  3. Concatenating the header, payload, and signature with dots

Example in Node.js:

const jwt = require("jsonwebtoken");

const payload = {
  clientId: "YOUR_CLIENT_ID",
  iat: Math.floor(Date.now() / 1000),
  exp: Math.floor(Date.now() / 1000) + 3600,
};

const jwtToken = jwt.sign(payload, "YOUR_API_KEY", {
  algorithm: "HS256",
});

Example in Python:

import jwt
import time

payload = {
    'clientId': 'YOUR_CLIENT_ID',
    'iat': int(time.time()),
    'exp': int(time.time()) + 3600
}

jwt_token = jwt.encode(payload, 'YOUR_API_KEY', algorithm='HS256')

Step 2: Exchange JWT for Access Token

Call the /auth/token endpoint with your generated JWT to receive access credentials.

Request

curl --location 'https://api.pitrade.com/public/auth/token' \
  --header 'Content-Type: application/json' \
  --data '{
    "token": "<GENERATED_JWT_TOKEN>"
  }'

Request Parameters

ParameterTypeRequiredDescription
tokenstringYesThe JWT token you created

Successful Response (Status 200)

{
  "AccessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "ExpiresIn": 3600,
  "TokenType": "Bearer",
  "RefreshToken": "refresh_token_value_here",
  "IdToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Response Parameters

ParameterTypeDescription
AccessTokenstringShort-lived access token (not used directly in APIs)
ExpiresInintegerToken expiration time in seconds (typically 3600 = 1 hour)
TokenTypestringAlways "Bearer"
RefreshTokenstringLong-lived token used to refresh expired credentials
IdTokenstringUse this token for all API requests (Bearer token)

Error Response (Status 401)

{
  "message": "Invalid or expired JWT token"
}

Step 3: Use Access Token for API Requests

Use the IdToken from the /auth/token response to authenticate all PiTrade API requests.

Request Header Format

Authorization: Bearer <ID_TOKEN>

Example API Request

curl --location 'https://api.pitrade.com/client/api/portfolios' \
  --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...' \
  --header 'Content-Type: application/json'

Token Refresh

When your IdToken expires, use the RefreshToken to obtain new credentials without regenerating the JWT.

Refresh Request

curl --location 'https://api.pitrade.com/public/auth/refresh' \
  --header 'Content-Type: application/json' \
  --data '{
    "refresh_token": "<REFRESH_TOKEN>"
  }'

Refresh Request Parameters

ParameterTypeRequiredDescription
refresh_tokenstringYesThe refresh token from auth/token response

Refresh Response (Status 200)

{
  "AccessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "ExpiresIn": 3600,
  "TokenType": "Bearer",
  "IdToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Refresh Response Parameters

ParameterTypeDescription
AccessTokenstringShort-lived access token
ExpiresInintegerToken expiration time in seconds
TokenTypestringAlways "Bearer"
IdTokenstringUse this as your new Bearer token

Refresh Error Response (Status 401)

{
  "message": "Invalid or expired refresh token"
}

Complete Authentication Example

Here's a complete end-to-end authentication flow:

1. Generate JWT Token

const jwt = require("jsonwebtoken");

function generateJWT() {
  const payload = {
    clientId: "YOUR_CLIENT_ID",
    iat: Math.floor(Date.now() / 1000),
    exp: Math.floor(Date.now() / 1000) + 3600,
  };

  return jwt.sign(payload, "YOUR_API_KEY", { algorithm: "HS256" });
}

const jwtToken = generateJWT();

2. Exchange for Access Token

async function getAccessToken(jwtToken) {
  const response = await fetch("https://api.pitrade.com/public/auth/token", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      token: jwtToken,
    }),
  });

  if (!response.ok) {
    throw new Error(`Authentication failed: ${response.status}`);
  }

  const data = await response.json();

  return data;
}

const tokens = await getAccessToken(jwtToken);

3. Make API Requests

async function makeAPIRequest(idToken) {
  const response = await fetch(
    "https://api.pitrade.com/client/api/portfolios",
    {
      method: "GET",
      headers: {
        Authorization: `Bearer ${idToken}`,
        "Content-Type": "application/json",
      },
    },
  );

  if (!response.ok) {
    throw new Error(`API request failed: ${response.status}`);
  }

  const data = await response.json();
  return data;
}

const apiData = await makeAPIRequest(tokens.IdToken);

4. Refresh Token When Needed

async function refreshAccessToken(refreshToken) {
  const response = await fetch("https://api.pitrade.com/public/auth/refresh", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      refresh_token: refreshToken,
    }),
  });

  if (!response.ok) {
    throw new Error(`Token refresh failed: ${response.status}`);
  }

  const data = await response.json();
  return data;
}

// When IdToken expires
const newTokens = await refreshAccessToken(tokens.RefreshToken);

More in PiTrade Client APIs

Was this page helpful?

PiTrade

PiTrade gives investors in over 190 countries access to the U.S. stock market through real, transparent portfolios you can build yourself or invest in Strategizer Portfolios. As an SEC-registered investment adviser, powered by Interactive Brokers, PiTrade makes investing more transparent and accessible.

This content is provided for informational purposes only and is not intended as and may not be relied on in any manner as investment advice, a recommendation of any interest in any security offered herein. All investments involve risk, including the possible loss of principal. Past performance does not guarantee future results, and investors should consider their own investment goals, risk tolerance, and financial situation before investing. The information contained herein is subject to change.

The platform "PiTrade" is operated by Pioneer Advisory LLC, a subsidiary of Pioneer Investing Inc. which holds ownership rights related hereto.

Advisory services are provided by Pioneer Advisory LLC, an SEC-registered investment adviser.

Brokerage and clearing services are provided by Interactive Brokers LLC, a SEC-registered broker-dealer, member FINRA/SIPC, to retail customers for US-listed, registered securities and ETFs on a self-directed basis.

The registrations and memberships above in no way imply that the SEC, FINRA, or SIPC has endorsed the entities, products or services discussed herein.

Interactive Brokers LLC is a registered Broker-Dealer, Futures Commission Merchant and Forex Dealer Member, regulated by the U.S. Securities and Exchange Commission (SEC), the Commodity Futures Trading Commission (CFTC) and the National Futures Association (NFA), and is a member of the Financial Industry Regulatory Authority (FINRA) and several other self-regulatory organizations. Interactive Brokers does not endorse or recommend any introducing brokers, third-party financial advisors or hedge funds, including Pioneer Advisory LLC. Interactive Brokers provides execution and clearing services to customers. None of the information contained herein constitutes a recommendation, offer, or solicitation of an offer by Interactive Brokers to buy, sell or hold any security, financial product or instrument or to engage in any specific investment strategy. Interactive Brokers makes no representation, and assumes no liability to the accuracy or completeness of the information provided on this website.

For more information regarding Interactive Brokers, please visit www.interactivebrokers.com

© 2026 Pioneer Investing Inc. All Rights Reserved.