- Installation
- Getting Started
-
Reference
snaptrade.accountInformation.getAllUserHoldings
snaptrade.accountInformation.getUserAccountBalance
snaptrade.accountInformation.getUserAccountDetails
snaptrade.accountInformation.getUserAccountOrders
snaptrade.accountInformation.getUserAccountPositions
snaptrade.accountInformation.getUserHoldings
snaptrade.accountInformation.listUserAccounts
snaptrade.accountInformation.updateUserAccount
snaptrade.apiStatus.check
snaptrade.authentication.deleteSnapTradeUser
snaptrade.authentication.getUserJWT
snaptrade.authentication.listSnapTradeUsers
snaptrade.authentication.loginSnapTradeUser
snaptrade.authentication.registerSnapTradeUser
snaptrade.authentication.resetSnapTradeUserSecret
snaptrade.connections.detailBrokerageAuthorization
snaptrade.connections.listBrokerageAuthorizations
snaptrade.connections.removeBrokerageAuthorization
snaptrade.connections.sessionEvents
snaptrade.options.getOptionStrategy
snaptrade.options.getOptionsChain
snaptrade.options.getOptionsStrategyQuote
snaptrade.options.listOptionHoldings
snaptrade.options.placeOptionStrategy
snaptrade.referenceData.getCurrencyExchangeRatePair
snaptrade.referenceData.getPartnerInfo
snaptrade.referenceData.getSecurityTypes
snaptrade.referenceData.getStockExchanges
snaptrade.referenceData.getSymbols
snaptrade.referenceData.getSymbolsByTicker
snaptrade.referenceData.listAllBrokerageAuthorizationType
snaptrade.referenceData.listAllBrokerages
snaptrade.referenceData.listAllCurrencies
snaptrade.referenceData.listAllCurrenciesRates
snaptrade.referenceData.symbolSearchUserAccount
snaptrade.trading.cancelUserAccountOrder
snaptrade.trading.getOrderImpact
snaptrade.trading.getUserAccountQuotes
snaptrade.trading.placeForceOrder
snaptrade.trading.placeOCOOrder
snaptrade.trading.placeOrder
snaptrade.transactionsAndReporting.getActivities
snaptrade.transactionsAndReporting.getReportingCustomRange
npm |
pnpm |
yarn |
---|---|---|
npm i snaptrade-typescript-sdk |
pnpm i snaptrade-typescript-sdk |
yarn add snaptrade-typescript-sdk |
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();
List all accounts for the user, plus balances, positions, and orders for each account.
const getAllUserHoldingsResponse =
await snaptrade.accountInformation.getAllUserHoldings({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
brokerageAuthorizations: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
});
Optional. Comma seperated list of authorization IDs (only use if filtering is needed on one or more authorizations).
/holdings
GET
A list of account balances for the specified account (one per currency that the account holds).
const getUserAccountBalanceResponse =
await snaptrade.accountInformation.getUserAccountBalance({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
});
The ID of the account to get balances.
/accounts/{accountId}/balances
GET
Return details of a specific investment account
const getUserAccountDetailsResponse =
await snaptrade.accountInformation.getUserAccountDetails({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
});
The ID of the account to get detail of.
/accounts/{accountId}
GET
Fetch all recent orders from a user's account.
const getUserAccountOrdersResponse =
await snaptrade.accountInformation.getUserAccountOrders({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
state: "all",
days: 30,
accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
});
The ID of the account to get orders.
defaults value is set to "all"
Number of days in the past to fetch the most recent orders. Defaults to the last 30 days if no value is passed in.
/accounts/{accountId}/orders
GET
List account positions
const getUserAccountPositionsResponse =
await snaptrade.accountInformation.getUserAccountPositions({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
});
The ID of the account to get positions.
/accounts/{accountId}/positions
GET
List balances, positions and orders for the specified account
const getUserHoldingsResponse =
await snaptrade.accountInformation.getUserHoldings({
accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
});
The ID of the account to fetch holdings for.
/accounts/{accountId}/holdings
GET
List accounts
const listUserAccountsResponse =
await snaptrade.accountInformation.listUserAccounts({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
});
/accounts
GET
Update details of an investment account
const updateUserAccountResponse =
await snaptrade.accountInformation.updateUserAccount({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
accountId: "accountId_example",
});
The ID of the account to update.
/accounts/{accountId}
PUT
Check whether the API is operational and verify timestamps.
const checkResponse = await snaptrade.apiStatus.check();
/
GET
Deletes a user you've registered over the SnapTrade API, and any data associated with them or their investment accounts.
const deleteSnapTradeUserResponse =
await snaptrade.authentication.deleteSnapTradeUser({
userId: "John.doe@snaptrade.com",
});
/snapTrade/deleteUser
DELETE
Generate encrypted JWT token
const getUserJWTResponse = await snaptrade.authentication.getUserJWT({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
});
/snapTrade/encryptedJWT
GET
Returns a list of users you've registered over the SnapTrade API.
const listSnapTradeUsersResponse =
await snaptrade.authentication.listSnapTradeUsers();
/snapTrade/listUsers
GET
Logs in a SnapTrade user and returns an authenticated connection portal URL for them to use to connect a brokerage account.
const loginSnapTradeUserResponse =
await snaptrade.authentication.loginSnapTradeUser({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
broker: "ALPACA",
immediateRedirect: true,
customRedirect: "https://snaptrade.com",
reconnect: "8b5f262d-4bb9-365d-888a-202bd3b15fa1",
connectionType: "read",
connectionPortalVersion: "v2",
});
Slug of the brokerage to connect the user to
When set to True, user will be redirected back to the partner\'s site instead of the connection portal
URL to redirect the user to after the user connects their brokerage account
The UUID of the brokerage connection to be reconnected. This parameter should be left empty unless you are reconnecting a disabled connection. See ‘Reconnecting Accounts’ for more information.
Sets whether the connection should be read or trade
Sets the version of the connection portal to render, with a default to \'v2\'
AuthenticationLoginSnapTradeUser200Response
/snapTrade/login
POST
Create SnapTrade user
const registerSnapTradeUserResponse =
await snaptrade.authentication.registerSnapTradeUser({
userId: "snaptrade-user-123",
});
SnapTrade User ID. Provided by SnapTrade Partner. Can be any string, as long as it\'s unique to a user
/snapTrade/registerUser
POST
Obtain a new user secret for a user
const resetSnapTradeUserSecretResponse =
await snaptrade.authentication.resetSnapTradeUserSecret({
userId: "snaptrade-user-123",
userSecret: "h81@cx1lkalablakwjaltkejraj11=",
});
SnapTrade User ID. Provided by SnapTrade Partner. Can be any string, as long as it\'s unique to a user
SnapTrade User Secret randomly generated by SnapTrade. This should be considered priviledged information and if compromised, you should delete and re-create this SnapTrade user.
/snapTrade/resetUserSecret
POST
Get brokerage authorization details
const detailBrokerageAuthorizationResponse =
await snaptrade.connections.detailBrokerageAuthorization({
authorizationId: "2bcd7cc3-e922-4976-bce1-9858296801c3",
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
});
The ID of a brokerage authorization object.
/authorizations/{authorizationId}
GET
List all brokerage authorizations for the user
const listBrokerageAuthorizationsResponse =
await snaptrade.connections.listBrokerageAuthorizations({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
});
/authorizations
GET
Delete brokerage authorization
const removeBrokerageAuthorizationResponse =
await snaptrade.connections.removeBrokerageAuthorization({
authorizationId: "2bcd7cc3-e922-4976-bce1-9858296801c3",
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
});
The ID of the Authorization to delete.
/authorizations/{authorizationId}
DELETE
List all session events for the partner
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",
});
Optional comma seperated list of user IDs used to filter the request on specific users
Optional comma seperated list of session IDs used to filter the request on specific users
ConnectionsSessionEvents200ResponseInner
/sessionEvents
GET
Creates an option strategy object that will be used to place an option strategy order
const getOptionStrategyResponse = await snaptrade.options.getOptionStrategy({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
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",
});
legs: OptionLeg
[]
The ID of the account to create the option strategy object in.
/accounts/{accountId}/optionStrategy
POST
Get the options chain
const getOptionsChainResponse = await snaptrade.options.getOptionsChain({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
accountId: "accountId_example",
symbol: "symbol_example",
});
The ID of the account to get the options chain from.
Universal symbol ID if symbol
/accounts/{accountId}/optionsChain
GET
Get latest market data of option strategy
const getOptionsStrategyQuoteResponse =
await snaptrade.options.getOptionsStrategyQuote({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
accountId: "accountId_example",
optionStrategyId: "2bcd7cc3-e922-4976-bce1-9858296801c3",
});
The ID of the account the strategy will be placed in.
Option strategy id obtained from response when creating option strategy object
/accounts/{accountId}/optionStrategy/{optionStrategyId}
GET
Get the options holdings in the account
const listOptionHoldingsResponse = await snaptrade.options.listOptionHoldings({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
accountId: "accountId_example",
});
The ID of the account to fetch options holdings for.
/accounts/{accountId}/options
GET
Place an option strategy order on the brokerage
const placeOptionStrategyResponse = await snaptrade.options.placeOptionStrategy(
{
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
accountId: "2bcd7cc3-e922-4976-bce1-9858296801c3",
optionStrategyId: "2bcd7cc3-e922-4976-bce1-9858296801c3",
order_type: "Limit",
time_in_force: "FOK",
price: 31.33,
}
);
order_type: OrderType
Order Type
time_in_force: TimeInForceStrict
Trade time in force examples: * FOK - Fill Or Kill * Day - Day * GTC - Good Til Canceled
The ID of the account to execute the strategy in.
Option strategy id obtained from response when creating option strategy object
Trade Price if limit or stop limit order
/accounts/{accountId}/optionStrategy/{optionStrategyId}/execute
POST
Return the exchange rate of a currency pair
const getCurrencyExchangeRatePairResponse =
await snaptrade.referenceData.getCurrencyExchangeRatePair({
currencyPair: "currencyPair_example",
});
A currency pair based on currency code for example, {CAD-USD}
/currencies/rates/{currencyPair}
GET
Get metadata related to Snaptrade partner
const getPartnerInfoResponse = await snaptrade.referenceData.getPartnerInfo();
/snapTrade/partners
GET
List security types available on SnapTrade.
const getSecurityTypesResponse =
await snaptrade.referenceData.getSecurityTypes();
/securityTypes
GET
List exchanges
const getStockExchangesResponse =
await snaptrade.referenceData.getStockExchanges();
/exchanges
GET
Search for symbols
const getSymbolsResponse = await snaptrade.referenceData.getSymbols({
substring: "apple",
});
/symbols
POST
Get details of a symbol by the ticker or the universal_symbol_id
const getSymbolsByTickerResponse =
await snaptrade.referenceData.getSymbolsByTicker({
query: "query_example",
});
The ticker or universal_symbol_id of the UniversalSymbol to get.
/symbols/{query}
GET
List of all brokerage authorization types
const listAllBrokerageAuthorizationTypeResponse =
await snaptrade.referenceData.listAllBrokerageAuthorizationType({
brokerage: "QUESTRADE,ALPACA",
});
Comma separated value of brokerage slugs
BrokerageAuthorizationTypeReadOnly
/brokerageAuthorizationTypes
GET
List brokerages
const listAllBrokeragesResponse =
await snaptrade.referenceData.listAllBrokerages();
/brokerages
GET
List currencies
const listAllCurrenciesResponse =
await snaptrade.referenceData.listAllCurrencies();
/currencies
GET
List currency exchange rates
const listAllCurrenciesRatesResponse =
await snaptrade.referenceData.listAllCurrenciesRates();
/currencies/rates
GET
Search for symbols available in an account
const symbolSearchUserAccountResponse =
await snaptrade.referenceData.symbolSearchUserAccount({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
substring: "apple",
});
The ID of the account to search for symbols within.
/accounts/{accountId}/symbols
POST
Cancel open order in account
const cancelUserAccountOrderResponse =
await snaptrade.trading.cancelUserAccountOrder({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
brokerage_order_id: "2bcd7cc3-e922-4976-bce1-9858296801c3",
});
The ID of the account to cancel the order in.
/accounts/{accountId}/orders/cancel
POST
Check impact of trades on account.
const getOrderImpactResponse = await snaptrade.trading.getOrderImpact({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
account_id: "2bcd7cc3-e922-4976-bce1-9858296801c3",
action: "BUY",
order_type: "Limit",
price: 31.33,
stop: 31.33,
time_in_force: "FOK",
universal_symbol_id: "2bcd7cc3-e922-4976-bce1-9858296801c3",
notional_value: 100,
});
action: Action
Trade Action
order_type: OrderType
Order Type
Trade Price if limit or stop limit order
Stop Price. If stop loss or stop limit order, the price to trigger the stop
time_in_force: TimeInForceStrict
Trade time in force examples: * FOK - Fill Or Kill * Day - Day * GTC - Good Til Canceled
units: number
notional_value: number
/trade/impact
POST
Get symbol quotes
const getUserAccountQuotesResponse =
await snaptrade.trading.getUserAccountQuotes({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
symbols: "symbols_example",
accountId: "917c8734-8470-4a3e-a18f-57c3f2ee6631",
});
List of universal_symbol_id or tickers to get quotes for.
The ID of the account to get quotes.
Should be set to True if providing tickers.
/accounts/{accountId}/quotes
GET
Place a trade with NO validation.
const placeForceOrderResponse = await snaptrade.trading.placeForceOrder({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
account_id: "2bcd7cc3-e922-4976-bce1-9858296801c3",
action: "BUY",
order_type: "Limit",
price: 31.33,
stop: 31.33,
time_in_force: "FOK",
universal_symbol_id: "2bcd7cc3-e922-4976-bce1-9858296801c3",
notional_value: 100,
});
action: Action
Trade Action
order_type: OrderType
Order Type
Trade Price if limit or stop limit order
Stop Price. If stop loss or stop limit order, the price to trigger the stop
time_in_force: TimeInForceStrict
Trade time in force examples: * FOK - Fill Or Kill * Day - Day * GTC - Good Til Canceled
units: number
notional_value: number
/trade/place
POST
Place a OCO (One Cancels Other) order
const placeOCOOrderResponse = await snaptrade.trading.placeOCOOrder({
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
});
The ID of first trade object obtained from trade/impact endpoint
The ID of second trade object obtained from trade/impact endpoint
/trade/oco
POST
Place order
const placeOrderResponse = await snaptrade.trading.placeOrder({
tradeId: "tradeId_example",
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
wait_to_confirm: true,
});
The ID of trade object obtained from trade/impact endpoint
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
/trade/{tradeId}
POST
Returns activities (transactions) for a user. Specifying start and end date is highly recommended for better performance
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: "DIVIDEND",
userId: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
});
Optional comma seperated list of account IDs used to filter the request on specific accounts
Optional comma seperated list of brokerage authorization IDs used to filter the request on only accounts that belong to those authorizations
Optional comma seperated list of types to filter activities by. This is not an exhaustive list, if we fail to match to these types, we will return the raw description from the brokerage. Potential values include - DIVIDEND - BUY - SELL - CONTRIBUTION - WITHDRAWAL - EXTERNAL_ASSET_TRANSFER_IN - EXTERNAL_ASSET_TRANSFER_OUT - INTERNAL_CASH_TRANSFER_IN - INTERNAL_CASH_TRANSFER_OUT - INTERNAL_ASSET_TRANSFER_IN - INTERNAL_ASSET_TRANSFER_OUT - INTEREST - REBATE - GOV_GRANT - TAX - FEE - REI - FXT
/activities
GET
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.
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: "John.doe@snaptrade.com",
userSecret: "USERSECRET123",
});
Optional comma seperated list of account IDs used to filter the request on specific accounts
Optional, increases frequency of data points for the total value and contribution charts if set to true
Optional frequency for the rate of return chart (defaults to monthly). Possible values are daily, weekly, monthly, quarterly, yearly.
/performance/custom
GET
This TypeScript package is automatically generated by Konfig