snaptrade-typescript-sdk
TypeScript icon, indicating that this package has built-in type declarations

9.0.99 • Public • Published

Visit SnapTrade

Connect brokerage accounts to your app for live positions and trading

npm More Info

Table of Contents

Installation

npm pnpm yarn
npm i snaptrade-typescript-sdk
pnpm i snaptrade-typescript-sdk
yarn add snaptrade-typescript-sdk

Getting Started

const { Snaptrade } = require("snaptrade-typescript-sdk");

async function main() {
  // 1) Initialize a client with your clientID and consumerKey.
  const snaptrade = new Snaptrade({
    consumerKey: process.env.SNAPTRADE_CONSUMER_KEY,
    clientId: process.env.SNAPTRADE_CLIENT_ID,
  });

  // 2) Check that the client is able to make a request to the API server.
  const status = await snaptrade.apiStatus.check();
  console.log("status:", status.data);

  // 3) Create a new user on SnapTrade
  const userId = uuid();
  const { userSecret } = (
    await snaptrade.authentication.registerSnapTradeUser({
      userId,
    })
  ).data;

  // Note: A user secret is only generated once. It's required to access
  // resources for certain endpoints.
  console.log("userSecret:", userSecret);

  // 4) Get a redirect URI. Users will need this to connect
  const data = (
    await snaptrade.authentication.loginSnapTradeUser({ userId, userSecret })
  ).data;
  if (!("redirectURI" in data)) throw Error("Should have gotten redirect URI");
  console.log("redirectURI:", data.redirectURI);

  // 5) Obtaining account holdings data
  const holdings = (
    await snaptrade.accountInformation.getAllUserHoldings({
      userId,
      userSecret,
    })
  ).data;
  console.log("holdings:", holdings);

  // 6) Deleting a user
  const deleteResponse = (
    await snaptrade.authentication.deleteSnapTradeUser({ userId })
  ).data;
  console.log("deleteResponse:", deleteResponse);
}

// Should be replaced with function to get user ID
function getUserId() {
  var d = new Date().getTime(); //Timestamp
  var d2 =
    (typeof performance !== "undefined" &&
      performance.now &&
      performance.now() * 1000) ||
    0; //Time in microseconds since page-load or 0 if unsupported
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = Math.random() * 16; //random number between 0 and 16
    if (d > 0) {
      //Use timestamp until depleted
      r = (d + r) % 16 | 0;
      d = Math.floor(d / 16);
    } else {
      //Use microseconds since page-load if supported
      r = (d2 + r) % 16 | 0;
      d2 = Math.floor(d2 / 16);
    }
    return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
  });
}

main();

Reference

snaptrade.accountInformation.getAccountActivities

Returns all historical transactions for the specified account.

This endpoint is paginated with a default page size of 1000. The endpoint will return a maximum of 1000 transactions per request. See the query parameters for pagination options.

Transaction are returned in reverse chronological order, using the trade_date field.

The data returned here is always cached and refreshed once a day.

🛠️ Usage

const getAccountActivitiesResponse =
  await snaptrade.accountInformation.getAccountActivities({
    accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
    startDate: "2022-01-24",
    endDate: "2022-01-24",
    type: "BUY,SELL,DIVIDEND",
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  });

⚙️ Parameters

accountId: string
userId: string
userSecret: string
startDate: string | Date

The start date (inclusive) of the transaction history to retrieve. If not provided, the default is the first transaction known to SnapTrade based on trade_date.

endDate: string | Date

The end date (inclusive) of the transaction history to retrieve. If not provided, the default is the last transaction known to SnapTrade based on trade_date.

offset: number

An integer that specifies the starting point of the paginated results. Default is 0.

limit: number

An integer that specifies the maximum number of transactions to return. Default of 1000.

type: string

Optional comma separated list of transaction types to filter by. SnapTrade does a best effort to categorize brokerage transaction types into a common set of values. Here are some of the most popular values: - BUY - Asset bought. - SELL - Asset sold. - DIVIDEND - Dividend payout. - CONTRIBUTION - Cash contribution. - WITHDRAWAL - Cash withdrawal. - REI - Dividend reinvestment. - STOCK_DIVIDEND - A type of dividend where a company distributes shares instead of cash - INTEREST - Interest deposited into the account. - FEE - Fee withdrawn from the account. - OPTIONEXPIRATION - Option expiration event. - OPTIONASSIGNMENT - Option assignment event. - OPTIONEXERCISE - Option exercise event. - TRANSFER - Transfer of assets from one account to another

🔄 Return

PaginatedUniversalActivity

🌐 Endpoint

/accounts/{accountId}/activities GET

🔙 Back to Table of Contents


snaptrade.accountInformation.getAllUserHoldings

Deprecated

Deprecated, please use the account-specific holdings endpoint instead.

List all accounts for the user, plus balances, positions, and orders for each account.

🛠️ Usage

const getAllUserHoldingsResponse =
  await snaptrade.accountInformation.getAllUserHoldings({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
    brokerageAuthorizations: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
  });

⚙️ Parameters

userId: string
userSecret: string
brokerageAuthorizations: string

Optional. Comma separated list of authorization IDs (only use if filtering is needed on one or more authorizations).

🔄 Return

AccountHoldings

🌐 Endpoint

/holdings GET

🔙 Back to Table of Contents


snaptrade.accountInformation.getUserAccountBalance

Returns a list of balances for the account. Each element of the list has a distinct currency. Some brokerages like Questrade allows holding multiple currencies in the same account.

The data returned here is cached. How long the data is cached for varies by brokerage. Check the brokerage integrations doc and look for "Cache Expiry Time" to see the exact value for a specific brokerage. If you need real-time data, please use the manual refresh endpoint.

🛠️ Usage

const getUserAccountBalanceResponse =
  await snaptrade.accountInformation.getUserAccountBalance({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
    accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
  });

⚙️ Parameters

userId: string
userSecret: string
accountId: string

🔄 Return

Balance

🌐 Endpoint

/accounts/{accountId}/balances GET

🔙 Back to Table of Contents


snaptrade.accountInformation.getUserAccountDetails

Returns account detail known to SnapTrade for the specified account.

The data returned here is always cached and refreshed once a day. If you need real-time data, please use the manual refresh endpoint.

🛠️ Usage

const getUserAccountDetailsResponse =
  await snaptrade.accountInformation.getUserAccountDetails({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
    accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
  });

⚙️ Parameters

userId: string
userSecret: string
accountId: string

🔄 Return

Account

🌐 Endpoint

/accounts/{accountId} GET

🔙 Back to Table of Contents


snaptrade.accountInformation.getUserAccountOrders

Returns a list of recent orders in the specified account.

The data returned here is cached. How long the data is cached for varies by brokerage. Check the brokerage integrations doc and look for "Cache Expiry Time" to see the exact value for a specific brokerage. If you need real-time data, please use the manual refresh endpoint.

🛠️ Usage

const getUserAccountOrdersResponse =
  await snaptrade.accountInformation.getUserAccountOrders({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
    state: "all",
    days: 30,
    accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
  });

⚙️ Parameters

userId: string
userSecret: string
accountId: string
state: 'all' | 'open' | 'executed'

defaults value is set to "all"

days: number

Number of days in the past to fetch the most recent orders. Defaults to the last 30 days if no value is passed in.

🔄 Return

AccountOrderRecord

🌐 Endpoint

/accounts/{accountId}/orders GET

🔙 Back to Table of Contents


snaptrade.accountInformation.getUserAccountPositions

Returns a list of stock/ETF/crypto/mutual fund positions in the specified account. For option positions, please use the options endpoint.

The data returned here is cached. How long the data is cached for varies by brokerage. Check the brokerage integrations doc and look for "Cache Expiry Time" to see the exact value for a specific brokerage. If you need real-time data, please use the manual refresh endpoint.

🛠️ Usage

const getUserAccountPositionsResponse =
  await snaptrade.accountInformation.getUserAccountPositions({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
    accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
  });

⚙️ Parameters

userId: string
userSecret: string
accountId: string

🔄 Return

Position

🌐 Endpoint

/accounts/{accountId}/positions GET

🔙 Back to Table of Contents


snaptrade.accountInformation.getUserAccountRecentOrders

A lightweight endpoint that returns a list of orders executed in the last 24 hours in the specified account. This endpoint is realtime and can be used to quickly check if account state has recently changed due to an execution, or check status of recently placed orders Differs from /orders in that it is realtime, and only checks the last 24 hours as opposed to the last 30 days By default only returns executed orders, but that can be changed by setting only_executed to false Please contact support for access as this endpoint is not enabled by default.

🛠️ Usage

const getUserAccountRecentOrdersResponse =
  await snaptrade.accountInformation.getUserAccountRecentOrders({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
    accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
  });

⚙️ Parameters

userId: string
userSecret: string
accountId: string
onlyExecuted: boolean

Defaults to true. Indicates if request should fetch only executed orders. Set to false to retrieve non executed orders as well

🔄 Return

RecentOrdersResponse

🌐 Endpoint

/accounts/{accountId}/recentOrders GET

🔙 Back to Table of Contents


snaptrade.accountInformation.getUserAccountReturnRates

Returns a list of rate of return percents for a given account. Will include timeframes available from the brokerage, for example "ALL", "1Y", "6M", "3M", "1M"

🛠️ Usage

const getUserAccountReturnRatesResponse =
  await snaptrade.accountInformation.getUserAccountReturnRates({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
    accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
  });

⚙️ Parameters

userId: string
userSecret: string
accountId: string

🔄 Return

RateOfReturnResponse

🌐 Endpoint

/accounts/{accountId}/returnRates GET

🔙 Back to Table of Contents


snaptrade.accountInformation.getUserHoldings

Returns a list of balances, positions, and recent orders for the specified account. The data returned is similar to the data returned over the more fine-grained balances, positions and orders endpoints. The finer-grained APIs are preferred. They are easier to work with, faster, and have better error handling than this coarse-grained API.

The data returned here is cached. How long the data is cached for varies by brokerage. Check the brokerage integrations doc and look for "Cache Expiry Time" to see the exact value for a specific brokerage. If you need real-time data, please use the manual refresh endpoint.

🛠️ Usage

const getUserHoldingsResponse =
  await snaptrade.accountInformation.getUserHoldings({
    accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  });

⚙️ Parameters

accountId: string
userId: string
userSecret: string

🔄 Return

AccountHoldingsAccount

🌐 Endpoint

/accounts/{accountId}/holdings GET

🔙 Back to Table of Contents


snaptrade.accountInformation.listUserAccounts

Returns all brokerage accounts across all connections known to SnapTrade for the authenticated user.

The data returned here is always cached and refreshed once a day. If you need real-time data, please use the manual refresh endpoint.

🛠️ Usage

const listUserAccountsResponse =
  await snaptrade.accountInformation.listUserAccounts({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  });

⚙️ Parameters

userId: string
userSecret: string

🔄 Return

Account

🌐 Endpoint

/accounts GET

🔙 Back to Table of Contents


snaptrade.accountInformation.updateUserAccount

Updates various properties of a specified account.

🛠️ Usage

const updateUserAccountResponse =
  await snaptrade.accountInformation.updateUserAccount({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
    accountId: "accountId_example",
  });

⚙️ Parameters

userId: string
userSecret: string
accountId: string

The ID of the account to update.

🔄 Return

Account

🌐 Endpoint

/accounts/{accountId} PUT

🔙 Back to Table of Contents


snaptrade.apiStatus.check

Check whether the API is operational and verify timestamps.

🛠️ Usage

const checkResponse = await snaptrade.apiStatus.check();

🔄 Return

Status

🌐 Endpoint

/ GET

🔙 Back to Table of Contents


snaptrade.authentication.deleteSnapTradeUser

Deletes a registered user and all associated data. This action is irreversible. This API is asynchronous and will return a 200 status code if the request is accepted. The user and all associated data will be queued for deletion. Once deleted, a USER_DELETED webhook will be sent.

🛠️ Usage

const deleteSnapTradeUserResponse =
  await snaptrade.authentication.deleteSnapTradeUser({
    userId: "snaptrade-user-123",
  });

⚙️ Parameters

userId: string

🔄 Return

DeleteUserResponse

🌐 Endpoint

/snapTrade/deleteUser DELETE

🔙 Back to Table of Contents


snaptrade.authentication.listSnapTradeUsers

Returns a list of all registered user IDs. Please note that the response is not currently paginated.

🛠️ Usage

const listSnapTradeUsersResponse =
  await snaptrade.authentication.listSnapTradeUsers();

🌐 Endpoint

/snapTrade/listUsers GET

🔙 Back to Table of Contents


snaptrade.authentication.loginSnapTradeUser

Authenticates a SnapTrade user and returns the Connection Portal URL used for connecting brokerage accounts. Please check this guide for how to integrate the Connection Portal into your app.

Please note that the returned URL expires in 5 minutes.

🛠️ Usage

const loginSnapTradeUserResponse =
  await snaptrade.authentication.loginSnapTradeUser({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
    broker: "ALPACA",
    immediateRedirect: true,
    customRedirect: "https://snaptrade.com",
    reconnect: "8b5f262d-4bb9-365d-888a-202bd3b15fa1",
    connectionType: "read",
    connectionPortalVersion: "v4",
  });

⚙️ Parameters

userId: string
userSecret: string
broker: string

Slug of the brokerage to connect the user to. See the integrations page for a list of supported brokerages and their slugs.

immediateRedirect: boolean

When set to true, user will be redirected back to the partner\'s site instead of the connection portal. This parameter is ignored if the connection portal is loaded inside an iframe. See the guide on ways to integrate the connection portal for more information.

customRedirect: string

URL to redirect the user to after the user connects their brokerage account. This parameter is ignored if the connection portal is loaded inside an iframe. See the guide on ways to integrate the connection portal for more information.

reconnect: string

The UUID of the brokerage connection to be reconnected. This parameter should be left empty unless you are reconnecting a disabled connection. See the guide on fixing broken connections for more information.

connectionType: string

Sets whether the connection should be read-only or trade-enabled. Defaults to read-only if not specified.

connectionPortalVersion: string

Sets the connection portal version to render. Currently only v4 is supported and is the default. All other versions are deprecated and will automatically be set to v4.

🔄 Return

AuthenticationLoginSnapTradeUser200Response

🌐 Endpoint

/snapTrade/login POST

🔙 Back to Table of Contents


snaptrade.authentication.registerSnapTradeUser

Registers a new SnapTrade user under your Client ID. A user secret will be automatically generated for you and must be properly stored in your system. Most SnapTrade operations require a user ID and user secret to be passed in as parameters.

🛠️ Usage

const registerSnapTradeUserResponse =
  await snaptrade.authentication.registerSnapTradeUser({
    userId: "snaptrade-user-123",
  });

⚙️ Parameters

userId: string

SnapTrade User ID. This is chosen by the API partner and can be any string that is a) unique to the user, and b) immutable for the user. It is recommended to NOT use email addresses for this property because they are usually not immutable.

🔄 Return

UserIDandSecret

🌐 Endpoint

/snapTrade/registerUser POST

🔙 Back to Table of Contents


snaptrade.authentication.resetSnapTradeUserSecret

Rotates the secret for a SnapTrade user. You might use this if userSecret is compromised. Please note that if you call this endpoint and fail to save the new secret, you'll no longer be able to access any data for this user, and your only option will be to delete and recreate the user, then ask them to reconnect.

🛠️ Usage

const resetSnapTradeUserSecretResponse =
  await snaptrade.authentication.resetSnapTradeUserSecret({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  });

⚙️ Parameters

userId: string

SnapTrade User ID. This is chosen by the API partner and can be any string that is a) unique to the user, and b) immutable for the user. It is recommended to NOT use email addresses for this property because they are usually not immutable.

userSecret: string

SnapTrade User Secret. This is a randomly generated string and should be stored securely. If compromised, please rotate it via the rotate user secret endpoint.

🔄 Return

UserIDandSecret

🌐 Endpoint

/snapTrade/resetUserSecret POST

🔙 Back to Table of Contents


snaptrade.connections.detailBrokerageAuthorization

Returns a single connection for the specified ID.

🛠️ Usage

const detailBrokerageAuthorizationResponse =
  await snaptrade.connections.detailBrokerageAuthorization({
    authorizationId: "87b24961-b51e-4db8-9226-f198f6518a89",
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  });

⚙️ Parameters

authorizationId: string
userId: string
userSecret: string

🔄 Return

BrokerageAuthorization

🌐 Endpoint

/authorizations/{authorizationId} GET

🔙 Back to Table of Contents


snaptrade.connections.disableBrokerageAuthorization

Manually force the specified connection to become disabled. This should only be used for testing a reconnect flow, and never used on production connections. Will trigger a disconnect as if it happened naturally, and send a CONNECTION_BROKEN webhook for the connection.

This endpoint is available on test keys. If you would like it enabled on production keys as well, please contact support as it is disabled by default.

🛠️ Usage

const disableBrokerageAuthorizationResponse =
  await snaptrade.connections.disableBrokerageAuthorization({
    authorizationId: "87b24961-b51e-4db8-9226-f198f6518a89",
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  });

⚙️ Parameters

authorizationId: string
userId: string
userSecret: string

🔄 Return

BrokerageAuthorizationDisabledConfirmation

🌐 Endpoint

/authorizations/{authorizationId}/disable POST

🔙 Back to Table of Contents


snaptrade.connections.listBrokerageAuthorizations

Returns a list of all connections for the specified user. Note that Connection and Brokerage Authorization are interchangeable, but the term Connection is preferred and used in the doc for consistency.

A connection is usually tied to a single login at a brokerage. A single connection can contain multiple brokerage accounts.

SnapTrade performs de-duping on connections for a given user. If the user has an existing connection with the brokerage, when connecting the brokerage with the same credentials, SnapTrade will return the existing connection instead of creating a new one.

🛠️ Usage

const listBrokerageAuthorizationsResponse =
  await snaptrade.connections.listBrokerageAuthorizations({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  });

⚙️ Parameters

userId: string
userSecret: string

🔄 Return

BrokerageAuthorization

🌐 Endpoint

/authorizations GET

🔙 Back to Table of Contents


snaptrade.connections.refreshBrokerageAuthorization

Trigger a holdings update for all accounts under this connection. Updates will be queued asynchronously. ACCOUNT_HOLDINGS_UPDATED webhook will be sent once the sync completes for each account under the connection. This endpoint will also trigger a transaction sync for the past day if one has not yet occurred.

Please contact support before use. Because of the cost of refreshing a connection, each call to this endpoint incurs a additional charge of $0.05

🛠️ Usage

const refreshBrokerageAuthorizationResponse =
  await snaptrade.connections.refreshBrokerageAuthorization({
    authorizationId: "87b24961-b51e-4db8-9226-f198f6518a89",
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  });

⚙️ Parameters

authorizationId: string
userId: string
userSecret: string

🔄 Return

BrokerageAuthorizationRefreshConfirmation

🌐 Endpoint

/authorizations/{authorizationId}/refresh POST

🔙 Back to Table of Contents


snaptrade.connections.removeBrokerageAuthorization

Deletes the connection specified by the ID. This will also delete all accounts and holdings associated with the connection. This action is irreversible. This endpoint is synchronous, a 204 response indicates that the connection has been successfully deleted.

🛠️ Usage

const removeBrokerageAuthorizationResponse =
  await snaptrade.connections.removeBrokerageAuthorization({
    authorizationId: "87b24961-b51e-4db8-9226-f198f6518a89",
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  });

⚙️ Parameters

authorizationId: string
userId: string
userSecret: string

🌐 Endpoint

/authorizations/{authorizationId} DELETE

🔙 Back to Table of Contents


snaptrade.connections.returnRates

Returns a list of rate of return percents for a given connection. Will include timeframes available from the brokerage, for example "ALL", "1Y", "6M", "3M", "1M"

🛠️ Usage

const returnRatesResponse = await snaptrade.connections.returnRates({
  userId: "snaptrade-user-123",
  userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  authorizationId: "87b24961-b51e-4db8-9226-f198f6518a89",
});

⚙️ Parameters

userId: string
userSecret: string
authorizationId: string

🔄 Return

RateOfReturnResponse

🌐 Endpoint

/authorizations/{authorizationId}/returnRates GET

🔙 Back to Table of Contents


snaptrade.connections.sessionEvents

Returns a list of session events associated with a user.

🛠️ Usage

const sessionEventsResponse = await snaptrade.connections.sessionEvents({
  partnerClientId: "SNAPTRADETEST",
  userId:
    "917c8734-8470-4a3e-a18f-57c3f2ee6631,65e839a3-9103-4cfb-9b72-2071ef80c5f2",
  sessionId:
    "917c8734-8470-4a3e-a18f-57c3f2ee6631,65e839a3-9103-4cfb-9b72-2071ef80c5f2",
});

⚙️ Parameters

partnerClientId: string
userId: string

Optional comma separated list of user IDs used to filter the request on specific users

sessionId: string

Optional comma separated list of session IDs used to filter the request on specific users

🔄 Return

ConnectionsSessionEvents200ResponseInner

🌐 Endpoint

/sessionEvents GET

🔙 Back to Table of Contents


snaptrade.options.getOptionStrategy

Creates an option strategy object that will be used to place an option strategy order.

🛠️ Usage

const getOptionStrategyResponse = await snaptrade.options.getOptionStrategy({
  userId: "snaptrade-user-123",
  userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  accountId: "accountId_example",
  underlying_symbol_id: "2bcd7cc3-e922-4976-bce1-9858296801c3",
  legs: [
    {
      action: "BUY_TO_OPEN",
      option_symbol_id: "SPY220819P00200000",
      quantity: 1,
    },
  ],
  strategy_type: "CUSTOM",
});

⚙️ Parameters

underlying_symbol_id: string
legs: OptionLeg[]
strategy_type: string
userId: string
userSecret: string
accountId: string

The ID of the account to create the option strategy object in.

🔄 Return

StrategyQuotes

🌐 Endpoint

/accounts/{accountId}/optionStrategy POST

🔙 Back to Table of Contents


snaptrade.options.getOptionsChain

Returns the option chain for the specified symbol in the specified account.

🛠️ Usage

const getOptionsChainResponse = await snaptrade.options.getOptionsChain({
  userId: "snaptrade-user-123",
  userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  accountId: "accountId_example",
  symbol: "symbol_example",
});

⚙️ Parameters

userId: string
userSecret: string
accountId: string

The ID of the account to get the options chain from.

symbol: string

Universal symbol ID if symbol

🔄 Return

OptionChainInner

🌐 Endpoint

/accounts/{accountId}/optionsChain GET

🔙 Back to Table of Contents


snaptrade.options.getOptionsStrategyQuote

Returns a Strategy Quotes object which has latest market data of the specified option strategy.

🛠️ Usage

const getOptionsStrategyQuoteResponse =
  await snaptrade.options.getOptionsStrategyQuote({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
    accountId: "accountId_example",
    optionStrategyId: "2bcd7cc3-e922-4976-bce1-9858296801c3",
  });

⚙️ Parameters

userId: string
userSecret: string
accountId: string

The ID of the account the strategy will be placed in.

optionStrategyId: string

Option strategy id obtained from response when creating option strategy object

🔄 Return

StrategyQuotes

🌐 Endpoint

/accounts/{accountId}/optionStrategy/{optionStrategyId} GET

🔙 Back to Table of Contents


snaptrade.options.listOptionHoldings

Returns a list of option positions in the specified account. For stock/ETF/crypto/mutual fund positions, please use the positions endpoint.

The data returned here is cached. How long the data is cached for varies by brokerage. Check the brokerage integrations doc and look for "Cache Expiry Time" to see the exact value for a specific brokerage. If you need real-time data, please use the manual refresh endpoint.

🛠️ Usage

const listOptionHoldingsResponse = await snaptrade.options.listOptionHoldings({
  userId: "snaptrade-user-123",
  userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
});

⚙️ Parameters

userId: string
userSecret: string
accountId: string

🔄 Return

OptionsPosition

🌐 Endpoint

/accounts/{accountId}/options GET

🔙 Back to Table of Contents


snaptrade.options.placeOptionStrategy

Places the option strategy order and returns the order record received from the brokerage.

🛠️ Usage

const placeOptionStrategyResponse = await snaptrade.options.placeOptionStrategy(
  {
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
    accountId: "2bcd7cc3-e922-4976-bce1-9858296801c3",
    optionStrategyId: "2bcd7cc3-e922-4976-bce1-9858296801c3",
    order_type: "Market",
    time_in_force: "Day",
    price: 31.33,
  }
);

⚙️ Parameters

order_type: OrderTypeStrict

The type of order to place. - For Limit and StopLimit orders, the price field is required. - For Stop and StopLimit orders, the stop field is required.

time_in_force: TimeInForceStrict

The Time in Force type for the order. This field indicates how long the order will remain active before it is executed or expires. Here are the supported values: - Day - Day. The order is valid only for the trading day on which it is placed. - GTC - Good Til Canceled. The order is valid until it is executed or canceled. - FOK - Fill Or Kill. The order must be executed in its entirety immediately or be canceled completely. - IOC - Immediate Or Cancel. The order must be executed immediately. Any portion of the order that cannot be filled immediately will be canceled.

userId: string
userSecret: string
accountId: string

The ID of the account to execute the strategy in.

optionStrategyId: string

Option strategy id obtained from response when creating option strategy object

price: number

Trade Price if limit or stop limit order

🔄 Return

StrategyOrderRecord

🌐 Endpoint

/accounts/{accountId}/optionStrategy/{optionStrategyId}/execute POST

🔙 Back to Table of Contents


snaptrade.referenceData.getCurrencyExchangeRatePair

Returns an Exchange Rate Pair object for the specified Currency Pair.

🛠️ Usage

const getCurrencyExchangeRatePairResponse =
  await snaptrade.referenceData.getCurrencyExchangeRatePair({
    currencyPair: "currencyPair_example",
  });

⚙️ Parameters

currencyPair: string

A currency pair based on currency code for example, {CAD-USD}

🔄 Return

ExchangeRatePairs

🌐 Endpoint

/currencies/rates/{currencyPair} GET

🔙 Back to Table of Contents


snaptrade.referenceData.getPartnerInfo

Returns configurations for your SnapTrade Client ID, including allowed brokerages and data access.

🛠️ Usage

const getPartnerInfoResponse = await snaptrade.referenceData.getPartnerInfo();

🔄 Return

PartnerData

🌐 Endpoint

/snapTrade/partners GET

🔙 Back to Table of Contents


snaptrade.referenceData.getSecurityTypes

Return all available security types supported by SnapTrade.

🛠️ Usage

const getSecurityTypesResponse =
  await snaptrade.referenceData.getSecurityTypes();

🔄 Return

SecurityType

🌐 Endpoint

/securityTypes GET

🔙 Back to Table of Contents


snaptrade.referenceData.getStockExchanges

Returns a list of all supported Exchanges.

🛠️ Usage

const getStockExchangesResponse =
  await snaptrade.referenceData.getStockExchanges();

🔄 Return

Exchange

🌐 Endpoint

/exchanges GET

🔙 Back to Table of Contents


snaptrade.referenceData.getSymbols

Returns a list of Universal Symbol objects that match the given query. The matching takes into consideration both the ticker and the name of the symbol. Only the first 20 results are returned.

🛠️ Usage

const getSymbolsResponse = await snaptrade.referenceData.getSymbols({
  substring: "AAPL",
});

⚙️ Parameters

substring: string

The search query for symbols.

🔄 Return

UniversalSymbol

🌐 Endpoint

/symbols POST

🔙 Back to Table of Contents


snaptrade.referenceData.getSymbolsByTicker

Returns the Universal Symbol object specified by the ticker or the Universal Symbol ID. When a ticker is specified, the first matching result is returned. We largely follow the Yahoo Finance ticker format(click on "Yahoo Finance Market Coverage and Data Delays"). For example, for securities traded on the Toronto Stock Exchange, the symbol has a '.TO' suffix. For securities traded on NASDAQ or NYSE, the symbol does not have a suffix. Please use the ticker with the proper suffix for the best results.

🛠️ Usage

const getSymbolsByTickerResponse =
  await snaptrade.referenceData.getSymbolsByTicker({
    query: "query_example",
  });

⚙️ Parameters

query: string

The ticker or Universal Symbol ID to look up the symbol with.

🔄 Return

UniversalSymbol

🌐 Endpoint

/symbols/{query} GET

🔙 Back to Table of Contents


snaptrade.referenceData.listAllBrokerageAuthorizationType

Returns a list of all defined Brokerage authorization Type objects.

🛠️ Usage

const listAllBrokerageAuthorizationTypeResponse =
  await snaptrade.referenceData.listAllBrokerageAuthorizationType({
    brokerage: "QUESTRADE,ALPACA",
  });

⚙️ Parameters

brokerage: string

Comma separated value of brokerage slugs

🔄 Return

BrokerageAuthorizationTypeReadOnly

🌐 Endpoint

/brokerageAuthorizationTypes GET

🔙 Back to Table of Contents


snaptrade.referenceData.listAllBrokerages

Returns a list of all defined Brokerage objects.

🛠️ Usage

const listAllBrokeragesResponse =
  await snaptrade.referenceData.listAllBrokerages();

🔄 Return

Brokerage

🌐 Endpoint

/brokerages GET

🔙 Back to Table of Contents


snaptrade.referenceData.listAllCurrencies

Returns a list of all defined Currency objects.

🛠️ Usage

const listAllCurrenciesResponse =
  await snaptrade.referenceData.listAllCurrencies();

🔄 Return

Currency

🌐 Endpoint

/currencies GET

🔙 Back to Table of Contents


snaptrade.referenceData.listAllCurrenciesRates

Returns a list of all Exchange Rate Pairs for all supported Currencies.

🛠️ Usage

const listAllCurrenciesRatesResponse =
  await snaptrade.referenceData.listAllCurrenciesRates();

🔄 Return

ExchangeRatePairs

🌐 Endpoint

/currencies/rates GET

🔙 Back to Table of Contents


snaptrade.referenceData.symbolSearchUserAccount

Returns a list of Universal Symbol objects that match the given query. The matching takes into consideration both the ticker and the name of the symbol. Only the first 20 results are returned.

The search results are further limited to the symbols supported by the brokerage for which the account is under.

🛠️ Usage

const symbolSearchUserAccountResponse =
  await snaptrade.referenceData.symbolSearchUserAccount({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
    accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
    substring: "AAPL",
  });

⚙️ Parameters

userId: string
userSecret: string
accountId: string
substring: string

The search query for symbols.

🔄 Return

UniversalSymbol

🌐 Endpoint

/accounts/{accountId}/symbols POST

🔙 Back to Table of Contents


snaptrade.trading.cancelOrder

Cancels an order in the specified account.

🛠️ Usage

const cancelOrderResponse = await snaptrade.trading.cancelOrder({
  userId: "snaptrade-user-123",
  userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
  brokerageOrderId: "66a033fa-da74-4fcf-b527-feefdec9257e",
});

⚙️ Parameters

userId: string
userSecret: string
accountId: string
brokerageOrderId: string

🔄 Return

OrderUpdatedResponse

🌐 Endpoint

/accounts/{accountId}/trading/simple/{brokerageOrderId}/cancel POST

🔙 Back to Table of Contents


snaptrade.trading.cancelUserAccountOrder

Attempts to cancel an open order with the brokerage. If the order is no longer cancellable, the request will be rejected.

🛠️ Usage

const cancelUserAccountOrderResponse =
  await snaptrade.trading.cancelUserAccountOrder({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
    accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
    brokerage_order_id: "66a033fa-da74-4fcf-b527-feefdec9257e",
  });

⚙️ Parameters

userId: string
userSecret: string
accountId: string
brokerage_order_id: string

Order ID returned by brokerage. This is the unique identifier for the order in the brokerage system.

🔄 Return

AccountOrderRecord

🌐 Endpoint

/accounts/{accountId}/orders/cancel POST

🔙 Back to Table of Contents


snaptrade.trading.getCryptocurrencyPairQuote

Gets a quote for the specified account.

🛠️ Usage

const getCryptocurrencyPairQuoteResponse =
  await snaptrade.trading.getCryptocurrencyPairQuote({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
    accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
    instrumentSymbol: "BTC-USD",
  });

⚙️ Parameters

userId: string
userSecret: string
accountId: string
instrumentSymbol: string

🔄 Return

CryptocurrencyPairQuote

🌐 Endpoint

/accounts/{accountId}/trading/instruments/cryptocurrencyPairs/{instrumentSymbol}/quote GET

🔙 Back to Table of Contents


snaptrade.trading.getOrderImpact

Simulates an order and its impact on the account. This endpoint does not place the order with the brokerage. If successful, it returns a Trade object and the ID of the object can be used to place the order with the brokerage using the place checked order endpoint. Please note that the Trade object returned expires after 5 minutes. Any order placed using an expired Trade will be rejected.

🛠️ Usage

const getOrderImpactResponse = await snaptrade.trading.getOrderImpact({
  userId: "snaptrade-user-123",
  userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  account_id: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
  action: "BUY",
  universal_symbol_id: "2bcd7cc3-e922-4976-bce1-9858296801c3",
  order_type: "Market",
  time_in_force: "Day",
  price: 31.33,
  stop: 31.33,
  units: 10.5,
});

⚙️ Parameters

account_id: string

Unique identifier for the connected brokerage account. This is the UUID used to reference the account in SnapTrade.

action: ActionStrict

The action describes the intent or side of a trade. This is either BUY or SELL.

universal_symbol_id: string

Unique identifier for the symbol within SnapTrade. This is the ID used to reference the symbol in SnapTrade API calls.

order_type: OrderTypeStrict

The type of order to place. - For Limit and StopLimit orders, the price field is required. - For Stop and StopLimit orders, the stop field is required.

time_in_force: TimeInForceStrict

The Time in Force type for the order. This field indicates how long the order will remain active before it is executed or expires. Here are the supported values: - Day - Day. The order is valid only for the trading day on which it is placed. - GTC - Good Til Canceled. The order is valid until it is executed or canceled. - FOK - Fill Or Kill. The order must be executed in its entirety immediately or be canceled completely. - IOC - Immediate Or Cancel. The order must be executed immediately. Any portion of the order that cannot be filled immediately will be canceled.

userId: string
userSecret: string
price: number

The limit price for Limit and StopLimit orders.

stop: number

The price at which a stop order is triggered for Stop and StopLimit orders.

units: number

🔄 Return

ManualTradeAndImpact

🌐 Endpoint

/trade/impact POST

🔙 Back to Table of Contents


snaptrade.trading.getUserAccountQuotes

Returns quotes from the brokerage for the specified symbols and account. The quotes returned can be delayed depending on the brokerage the account belongs to. It is highly recommended that you use your own market data provider for real-time quotes instead of relying on this endpoint. This endpoint does not work for options quotes.

🛠️ Usage

const getUserAccountQuotesResponse =
  await snaptrade.trading.getUserAccountQuotes({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
    symbols: "symbols_example",
    accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
  });

⚙️ Parameters

userId: string
userSecret: string
symbols: string

List of Universal Symbol IDs or tickers to get quotes for. When providing multiple values, use a comma as separator

accountId: string
useTicker: boolean

Should be set to True if symbols are comprised of tickers. Defaults to False if not provided.

🔄 Return

SymbolsQuotesInner

🌐 Endpoint

/accounts/{accountId}/quotes GET

🔙 Back to Table of Contents


snaptrade.trading.placeBracketOrder

Places a bracket order (entry order + OCO of stop loss and take profit). Disabled by default please contact support for use. Only supported on certain brokerages

🛠️ Usage

const placeBracketOrderResponse = await snaptrade.trading.placeBracketOrder({
  accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
  userId: "snaptrade-user-123",
  userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  action: "BUY",
  symbol: "AAPL",
  instrument: {
    symbol: "AAPL",
    type: "EQUITY",
  },
  order_type: "Market",
  time_in_force: "Day",
  price: 31.33,
  stop: 31.33,
  units: 10.5,
  stop_loss: {
    stop_price: "48.55",
    limit_price: "48.50",
  },
  take_profit: {
    limit_price: "49.95",
  },
});

⚙️ Parameters

The action describes the intent or side of a trade. This is either BUY or SELL for Equity symbols or BUY_TO_OPEN, BUY_TO_CLOSE, SELL_TO_OPEN or SELL_TO_CLOSE for Options.

instrument: TradingInstrument
order_type: OrderTypeStrict

The type of order to place. - For Limit and StopLimit orders, the price field is required. - For Stop and StopLimit orders, the stop field is required.

time_in_force: TimeInForceStrict

The Time in Force type for the order. This field indicates how long the order will remain active before it is executed or expires. Here are the supported values: - Day - Day. The order is valid only for the trading day on which it is placed. - GTC - Good Til Canceled. The order is valid until it is executed or canceled. - FOK - Fill Or Kill. The order must be executed in its entirety immediately or be canceled completely. - IOC - Immediate Or Cancel. The order must be executed immediately. Any portion of the order that cannot be filled immediately will be canceled.

stop_loss: StopLoss
take_profit: TakeProfit
accountId: string

The ID of the account to execute the trade on.

userId: string
userSecret: string
symbol: string

The security\'s trading ticker symbol.

price: number

The limit price for Limit and StopLimit orders.

stop: number

The price at which a stop order is triggered for Stop and StopLimit orders.

units: number

Number of shares for the order. This can be a decimal for fractional orders. Must be null if notional_value is provided.

🔄 Return

AccountOrderRecord

🌐 Endpoint

/accounts/{accountId}/trading/bracket POST

🔙 Back to Table of Contents


snaptrade.trading.placeForceOrder

Places a brokerage order in the specified account. The order could be rejected by the brokerage if it is invalid or if the account does not have sufficient funds.

This endpoint does not compute the impact to the account balance from the order and any potential commissions before submitting the order to the brokerage. If that is desired, you can use the check order impact endpoint.

It's recommended to trigger a manual refresh of the account after placing an order to ensure the account is up to date. You can use the manual refresh endpoint for this.

🛠️ Usage

const placeForceOrderResponse = await snaptrade.trading.placeForceOrder({
  userId: "snaptrade-user-123",
  userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  account_id: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
  action: "BUY",
  universal_symbol_id: "2bcd7cc3-e922-4976-bce1-9858296801c3",
  symbol: "AAPL  131124C00240000",
  order_type: "Market",
  time_in_force: "Day",
  price: 31.33,
  stop: 31.33,
  units: 10.5,
});

⚙️ Parameters

account_id: string

Unique identifier for the connected brokerage account. This is the UUID used to reference the account in SnapTrade.

The action describes the intent or side of a trade. This is either BUY or SELL for Equity symbols or BUY_TO_OPEN, BUY_TO_CLOSE, SELL_TO_OPEN or SELL_TO_CLOSE for Options.

order_type: OrderTypeStrict

The type of order to place. - For Limit and StopLimit orders, the price field is required. - For Stop and StopLimit orders, the stop field is required.

time_in_force: TimeInForceStrict

The Time in Force type for the order. This field indicates how long the order will remain active before it is executed or expires. Here are the supported values: - Day - Day. The order is valid only for the trading day on which it is placed. - GTC - Good Til Canceled. The order is valid until it is executed or canceled. - FOK - Fill Or Kill. The order must be executed in its entirety immediately or be canceled completely. - IOC - Immediate Or Cancel. The order must be executed immediately. Any portion of the order that cannot be filled immediately will be canceled.

userId: string
userSecret: string
universal_symbol_id: string

The universal symbol ID of the security to trade. Must be \'null\' if symbol is provided, otherwise must be provided.

symbol: string

The security\'s trading ticker symbol. This currently supports stock symbols and Options symbols in the 21 character OCC format. For example \"AAPL 131124C00240000\" represents a call option on AAPL expiring on 2024-11-13 with a strike price of $240. For more information on the OCC format, see here. If \'symbol\' is provided, then \'universal_symbol_id\' must be \'null\'.

price: number

The limit price for Limit and StopLimit orders.

stop: number

The price at which a stop order is triggered for Stop and StopLimit orders.

units: number

For Equity orders, this represents the number of shares for the order. This can be a decimal for fractional orders. Must be null if notional_value is provided. If placing an Option order, this field represents the number of contracts to buy or sell. (e.g., 1 contract = 100 shares).

🔄 Return

AccountOrderRecord

🌐 Endpoint

/trade/place POST

🔙 Back to Table of Contents


snaptrade.trading.placeMlegOrder

Places a multi-leg option order. Only supported on certain option trading brokerages. https://snaptrade.notion.site/brokerages has information on brokerage trading support

🛠️ Usage

const placeMlegOrderResponse = await snaptrade.trading.placeMlegOrder({
  userId: "snaptrade-user-123",
  userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
  type: "MARKET",
  time_in_force: "Day",
  limit_price: "",
  stop_price: "",
  legs: [
    {
      instrument: {
        symbol: "PBI   250718C00006000",
        type: "OPTION",
      },
      action: "BUY_TO_OPEN",
      units: 1,
    },
  ],
});

⚙️ Parameters

type: string

The type of order to place.

time_in_force: TimeInForceStrict

The Time in Force type for the order. This field indicates how long the order will remain active before it is executed or expires. Here are the supported values: - Day - Day. The order is valid only for the trading day on which it is placed. - GTC - Good Til Canceled. The order is valid until it is executed or canceled. - FOK - Fill Or Kill. The order must be executed in its entirety immediately or be canceled completely. - IOC - Immediate Or Cancel. The order must be executed immediately. Any portion of the order that cannot be filled immediately will be canceled.

legs: MlegLeg[]
userId: string
userSecret: string
accountId: string
limit_price: string

The limit price. Required if the order type is LIMIT, STOP_LOSS_LIMIT.

stop_price: string

The stop price. Required if the order type is STOP_LOSS_MARKET, STOP_LOSS_LIMIT.

🔄 Return

MlegOrderResponse

🌐 Endpoint

/accounts/{accountId}/trading/options POST

🔙 Back to Table of Contents


snaptrade.trading.placeOrder

Places the previously checked order with the brokerage. The tradeId is obtained from the check order impact endpoint. If you prefer to place the order without checking for impact first, you can use the place order endpoint.

It's recommended to trigger a manual refresh of the account after placing an order to ensure the account is up to date. You can use the manual refresh endpoint for this.

🛠️ Usage

const placeOrderResponse = await snaptrade.trading.placeOrder({
  tradeId: "139e307a-82f7-4402-b39e-4da7baa87758",
  userId: "snaptrade-user-123",
  userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  wait_to_confirm: true,
});

⚙️ Parameters

tradeId: string

Obtained from calling the check order impact endpoint

userId: string
userSecret: string
wait_to_confirm: boolean

Optional, defaults to true. Determines if a wait is performed to check on order status. If false, latency will be reduced but orders returned will be more likely to be of status PENDING as we will not wait to check on the status before responding to the request.

🔄 Return

AccountOrderRecord

🌐 Endpoint

/trade/{tradeId} POST

🔙 Back to Table of Contents


snaptrade.trading.placeSimpleOrder

Places an order in the specified account. This endpoint does not compute the impact to the account balance from the order before submitting the order.

🛠️ Usage

const placeSimpleOrderResponse = await snaptrade.trading.placeSimpleOrder({
  userId: "snaptrade-user-123",
  userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
  instrument: {
    symbol: "AAPL",
    type: "EQUITY",
  },
  side: "BUY",
  type: "MARKET",
  time_in_force: "GTC",
  amount: "123.45",
  limit_price: "123.45",
  stop_price: "123.45",
  post_only: false,
  expiration_date: "2024-01-01T00:00:00Z",
});

⚙️ Parameters

instrument: TradingInstrument

The action describes the intent or side of a trade. This is either BUY or SELL.

type: string

The type of order to place.

time_in_force: string

The Time in Force type for the order. This field indicates how long the order will remain active before it is executed or expires. - GTC - Good Til Canceled. The order is valid until it is executed or canceled. - FOK - Fill Or Kill. The order must be executed in its entirety immediately or be canceled completely. - IOC - Immediate Or Cancel. The order must be executed immediately. Any portion of the order that cannot be filled immediately will be canceled. - GTD - Good Til Date. The order is valid until the specified date.

amount: string

The amount of the base currency to buy or sell.

userId: string
userSecret: string
accountId: string
limit_price: string

The limit price. Required if the order type is LIMIT, STOP_LOSS_LIMIT or TAKE_PROFIT_LIMIT.

stop_price: string

The stop price. Required if the order type is STOP_LOSS_MARKET, STOP_LOSS_LIMIT, TAKE_PROFIT_MARKET or TAKE_PROFIT_LIMIT.

post_only: boolean

Valid and required only for order type LIMIT. If true orders that would be filled immediately are rejected to avoid incurring TAKER fees.

expiration_date: string

The expiration date of the order. Required if the time_in_force is GTD.

🔄 Return

OrderUpdatedResponse

🌐 Endpoint

/accounts/{accountId}/trading/simple POST

🔙 Back to Table of Contents


snaptrade.trading.previewSimpleOrder

Previews an order using the specified account.

🛠️ Usage

const previewSimpleOrderResponse = await snaptrade.trading.previewSimpleOrder({
  userId: "snaptrade-user-123",
  userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
  instrument: {
    symbol: "AAPL",
    type: "EQUITY",
  },
  side: "BUY",
  type: "MARKET",
  time_in_force: "GTC",
  amount: "123.45",
  limit_price: "123.45",
  stop_price: "123.45",
  post_only: false,
  expiration_date: "2024-01-01T00:00:00Z",
});

⚙️ Parameters

instrument: TradingInstrument

The action describes the intent or side of a trade. This is either BUY or SELL.

type: string

The type of order to place.

time_in_force: string

The Time in Force type for the order. This field indicates how long the order will remain active before it is executed or expires. - GTC - Good Til Canceled. The order is valid until it is executed or canceled. - FOK - Fill Or Kill. The order must be executed in its entirety immediately or be canceled completely. - IOC - Immediate Or Cancel. The order must be executed immediately. Any portion of the order that cannot be filled immediately will be canceled. - GTD - Good Til Date. The order is valid until the specified date.

amount: string

The amount of the base currency to buy or sell.

userId: string
userSecret: string
accountId: string
limit_price: string

The limit price. Required if the order type is LIMIT, STOP_LOSS_LIMIT or TAKE_PROFIT_LIMIT.

stop_price: string

The stop price. Required if the order type is STOP_LOSS_MARKET, STOP_LOSS_LIMIT, TAKE_PROFIT_MARKET or TAKE_PROFIT_LIMIT.

post_only: boolean

Valid and required only for order type LIMIT. If true orders that would be filled immediately are rejected to avoid incurring TAKER fees.

expiration_date: string

The expiration date of the order. Required if the time_in_force is GTD.

🔄 Return

SimpleOrderPreview

🌐 Endpoint

/accounts/{accountId}/trading/simple/preview POST

🔙 Back to Table of Contents


snaptrade.trading.replaceOrder

Replaces an existing pending order with a new one. The way this works is brokerage dependent, but usually involves cancelling the existing order and placing a new one. The order's brokerage_order_id may or may not change, be sure to use the one returned in the response going forward. Only supported on some brokerages

🛠️ Usage

const replaceOrderResponse = await snaptrade.trading.replaceOrder({
  accountId: "2bcd7cc3-e922-4976-bce1-9858296801c3",
  brokerageOrderId: "66a033fa-da74-4fcf-b527-feefdec9257e",
  userId: "snaptrade-user-123",
  userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  action: "BUY",
  order_type: "Market",
  time_in_force: "Day",
  price: 31.33,
  symbol: "AAPL",
  stop: 31.33,
  units: 10.5,
});

⚙️ Parameters

action: ActionStrict

The action describes the intent or side of a trade. This is either BUY or SELL.

order_type: OrderTypeStrict

The type of order to place. - For Limit and StopLimit orders, the price field is required. - For Stop and StopLimit orders, the stop field is required.

time_in_force: TimeInForceStrict

The Time in Force type for the order. This field indicates how long the order will remain active before it is executed or expires. Here are the supported values: - Day - Day. The order is valid only for the trading day on which it is placed. - GTC - Good Til Canceled. The order is valid until it is executed or canceled. - FOK - Fill Or Kill. The order must be executed in its entirety immediately or be canceled completely. - IOC - Immediate Or Cancel. The order must be executed immediately. Any portion of the order that cannot be filled immediately will be canceled.

accountId: string

The ID of the account to execute the trade on.

brokerageOrderId: string

The Brokerage Order ID of the order to replace.

userId: string
userSecret: string
price: number

The limit price for Limit and StopLimit orders.

symbol: string

The security\'s trading ticker symbol

stop: number

The price at which a stop order is triggered for Stop and StopLimit orders.

units: number

🔄 Return

AccountOrderRecord

🌐 Endpoint

/accounts/{accountId}/trading/simple/{brokerageOrderId}/replace PATCH

🔙 Back to Table of Contents


snaptrade.trading.searchCryptocurrencyPairInstruments

Searches cryptocurrency pairs instruments accessible to the specified account.

🛠️ Usage

const searchCryptocurrencyPairInstrumentsResponse =
  await snaptrade.trading.searchCryptocurrencyPairInstruments({
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
    accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
    base: "BTC",
    quote: "USD",
  });

⚙️ Parameters

userId: string
userSecret: string
accountId: string
base: string
quote: string

🔄 Return

TradingSearchCryptocurrencyPairInstruments200Response

🌐 Endpoint

/accounts/{accountId}/trading/instruments/cryptocurrencyPairs GET

🔙 Back to Table of Contents


snaptrade.transactionsAndReporting.getActivities

Deprecated

This endpoint is being deprecated but will continue to be available for use via SDKs, please use the account level endpoint if possible

Returns all historical transactions for the specified user and filtering criteria. It's recommended to use startDate and endDate to paginate through the data, as the response may be very large for accounts with a long history and/or a lot of activity. There's a max number of 10000 transactions returned per request.

There is no guarantee to the ordering of the transactions returned. Please sort the transactions based on the trade_date field if you need them in a specific order.

The data returned here is always cached and refreshed once a day.

🛠️ Usage

const getActivitiesResponse =
  await snaptrade.transactionsAndReporting.getActivities({
    startDate: "2022-01-24",
    endDate: "2022-01-24",
    accounts:
      "917c8734-8470-4a3e-a18f-57c3f2ee6631,65e839a3-9103-4cfb-9b72-2071ef80c5f2",
    brokerageAuthorizations:
      "917c8734-8470-4a3e-a18f-57c3f2ee6631,65e839a3-9103-4cfb-9b72-2071ef80c5f2",
    type: "BUY,SELL,DIVIDEND",
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  });

⚙️ Parameters

userId: string
userSecret: string
startDate: string | Date

The start date (inclusive) of the transaction history to retrieve. If not provided, the default is the first transaction known to SnapTrade based on trade_date.

endDate: string | Date

The end date (inclusive) of the transaction history to retrieve. If not provided, the default is the last transaction known to SnapTrade based on trade_date.

accounts: string

Optional comma separated list of SnapTrade Account IDs used to filter the request to specific accounts. If not provided, the default is all known brokerage accounts for the user. The brokerageAuthorizations parameter takes precedence over this parameter.

brokerageAuthorizations: string

Optional comma separated list of SnapTrade Connection (Brokerage Authorization) IDs used to filter the request to only accounts that belong to those connections. If not provided, the default is all connections for the user. This parameter takes precedence over the accounts parameter.

type: string

Optional comma separated list of transaction types to filter by. SnapTrade does a best effort to categorize brokerage transaction types into a common set of values. Here are some of the most popular values: - BUY - Asset bought. - SELL - Asset sold. - DIVIDEND - Dividend payout. - CONTRIBUTION - Cash contribution. - WITHDRAWAL - Cash withdrawal. - REI - Dividend reinvestment. - INTEREST - Interest deposited into the account. - FEE - Fee withdrawn from the account. - OPTIONEXPIRATION - Option expiration event. - OPTIONASSIGNMENT - Option assignment event. - OPTIONEXERCISE - Option exercise event. - TRANSFER - Transfer of assets from one account to another

🔄 Return

UniversalActivity

🌐 Endpoint

/activities GET

🔙 Back to Table of Contents


snaptrade.transactionsAndReporting.getReportingCustomRange

Deprecated

Returns performance information (contributions, dividends, rate of return, etc) for a specific timeframe. Please note that Total Equity Timeframe and Rate of Returns are experimental features. Please contact support@snaptrade.com if you notice any inconsistencies.

🛠️ Usage

const getReportingCustomRangeResponse =
  await snaptrade.transactionsAndReporting.getReportingCustomRange({
    startDate: "2022-01-24",
    endDate: "2022-01-24",
    accounts:
      "917c8734-8470-4a3e-a18f-57c3f2ee6631,65e839a3-9103-4cfb-9b72-2071ef80c5f2",
    detailed: true,
    frequency: "monthly",
    userId: "snaptrade-user-123",
    userSecret: "adf2aa34-8219-40f7-a6b3-60156985cc61",
  });

⚙️ Parameters

startDate: string | Date
endDate: string | Date
userId: string
userSecret: string
accounts: string

Optional comma separated list of account IDs used to filter the request on specific accounts

detailed: boolean

Optional, increases frequency of data points for the total value and contribution charts if set to true

frequency: string

Optional frequency for the rate of return chart (defaults to monthly). Possible values are daily, weekly, monthly, quarterly, yearly.

🔄 Return

PerformanceCustom

🌐 Endpoint

/performance/custom GET

🔙 Back to Table of Contents


Author

This TypeScript package is automatically generated by Konfig

Package Sidebar

Install

npm i snaptrade-typescript-sdk

Weekly Downloads

2,147

Version

9.0.99

License

Unlicense

Unpacked Size

1.08 MB

Total Files

335

Last publish

Collaborators

  • dphuang2
  • snaptrade
  • konfig-publisher