### SnapTrade Go SDK Getting Started Example Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/go/README.md A complete example demonstrating how to initialize the SnapTrade client, register a user, obtain a login redirect URI, list brokerage connections and accounts, and delete a user. Ensure SNAPTRADE_CLIENT_ID and SNAPTRADE_CONSUMER_KEY environment variables are set. ```go package main import ( "bufio" "crypto/rand" "fmt" "os" snaptrade "github.com/passiv/snaptrade-sdks/sdks/go" ) func main() { // 1) Initialize a client with your clientID and consumerKey. configuration := snaptrade.NewConfiguration() configuration.SetPartnerClientId(os.Getenv("SNAPTRADE_CLIENT_ID")) configuration.SetConsumerKey(os.Getenv("SNAPTRADE_CONSUMER_KEY")) client := snaptrade.NewAPIClient(configuration) // 2) Check that the client is able to make a request to the API server. apiResponse, _, _ := client.APIStatusApi.Check().Execute() fmt.Println(apiResponse) // 3) Create a new user on SnapTrade userId := generateUUID() requestBody := snaptrade.NewSnapTradeRegisterUserRequestBody(userId) request := client.AuthenticationApi.RegisterSnapTradeUser(*requestBody) registerResponse, _, _ := request.Execute() fmt.Println(registerResponse) // Note: A user secret is only generated once. It's required to access // resources for certain endpoints. userSecret := registerResponse.GetUserSecret() // 4) Get a redirect URI. Users will need this to connect // their brokerage to the SnapTrade server. redirectURI, _, _ := client.AuthenticationApi.LoginSnapTradeUser(userId, userSecret).Execute() if redirectURI.LoginRedirectURI != nil { fmt.Println(redirectURI.LoginRedirectURI.GetRedirectURI()) } else { fmt.Println(redirectURI) } fmt.Print("Open the link in your browser. When done logging in, press Enter to continue...") _, _ = bufio.NewReader(os.Stdin).ReadString('\n') // 5) Get a list of connections connections, _, _ := client.ConnectionsApi.ListBrokerageAuthorizations(userId, userSecret).Execute() fmt.Println(connections) // 6) Get a list of accounts for the first connection, if available if len(connections) == 0 { fmt.Println("No brokerage connections found for the user.") } else { accounts, _, _ := client.ConnectionsApi.ListBrokerageAuthorizationAccounts( connections[0].GetId(), userId, userSecret, ).Execute() fmt.Println(accounts) } // 6) Deleting a user deleteResp, _, _ := client.AuthenticationApi.DeleteSnapTradeUser(userId).Execute() fmt.Println(deleteResp) } func generateUUID() string { bytes := make([]byte, 16) if _, err := rand.Read(bytes); err != nil { panic(err) } bytes[6] = (bytes[6] & 0x0f) | 0x40 bytes[8] = (bytes[8] & 0x3f) | 0x80 return fmt.Sprintf("%x-%x-%x-%x-%x", bytes[0:4], bytes[4:6], bytes[6:8], bytes[8:10], bytes[10:]) } ``` -------------------------------- ### Snaptrade SDK Getting Started Example Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/typescript/README.md A comprehensive example demonstrating how to initialize the Snaptrade client, check API status, register a user, get a redirect URI, list connections and accounts, and delete a user. ```typescript const { Snaptrade } = require("snaptrade-typescript-sdk"); const { randomUUID } = require("crypto"); const readline = require("readline"); 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 = randomUUID(); const registerResponse = ( await snaptrade.authentication.registerSnapTradeUser({ userId, }) ).data; console.log("registerResponse:", registerResponse); // Note: A user secret is only generated once. It's required to access // resources for certain endpoints. const userSecret = registerResponse.userSecret; // 4) Get a redirect URI. Users will need this to connect // their brokerage to the SnapTrade server. const redirectURI = ( await snaptrade.authentication.loginSnapTradeUser({ userId, userSecret }) ).data; console.log("redirectURI:", redirectURI); await waitForEnter( "Open the link in your browser. When done logging in, press Enter to continue..." ); // 5) Get a list of connections const connections = ( await snaptrade.connections.listBrokerageAuthorizations({ userId, userSecret, }) ).data; console.log("connections:", connections); // 6) Get a list of accounts for the first connection, if available if (!Array.isArray(connections) || connections.length === 0) { console.log("No brokerage connections found for the user."); } else { const accounts = ( await snaptrade.connections.listBrokerageAuthorizationAccounts({ authorizationId: connections[0].id, userId, userSecret, }) ).data; console.log("accounts:", accounts); } // 6) Deleting a user const deleteResponse = ( await snaptrade.authentication.deleteSnapTradeUser({ userId }) ).data; console.log("deleteResponse:", deleteResponse); } function waitForEnter(prompt) { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); return new Promise((resolve) => { rl.question(prompt, () => { rl.close(); resolve(); }); }); } main(); ``` -------------------------------- ### SnapTrade Python SDK Getting Started Guide Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/python/README.md A comprehensive guide to initializing the SnapTrade client, registering a user, obtaining a redirect URI for brokerage connection, listing connections and accounts, and deleting a user. ```python import os import uuid from pprint import pprint from typing import List from snaptrade_client import SnapTrade # 1) Initialize a client with your clientID and consumerKey. snaptrade = SnapTrade( consumer_key=os.environ["SNAPTRADE_CONSUMER_KEY"], client_id=os.environ["SNAPTRADE_CLIENT_ID"], ) # 2) Check that the client is able to make a request to the API server. api_response = snaptrade.api_status.check() pprint(api_response.body) # 3) Create a new user on SnapTrade user_id = str(uuid.uuid4()) register_response = snaptrade.authentication.register_snap_trade_user( body={"userId": user_id} ) pprint(register_response.body) # Note: A user secret is only generated once. It's required to access # resources for certain endpoints. user_secret = register_response.body["userSecret"] # 4) Get a redirect URI. Users will need this to connect # their brokerage to the SnapTrade server. redirect_uri = snaptrade.authentication.login_snap_trade_user( query_params={"userId": user_id, "userSecret": user_secret} ) print(redirect_uri.body) input("Open the link in your browser. When done logging in, press Enter to continue...") # 5) Get a list of connections connections = snaptrade.connections.list( query_params={"userId": user_id, "userSecret": user_secret} ) pprint(connections.body) # 6) Get a list of accounts for the first connection, if available if not isinstance(connections.body, List) or len(connections.body) == 0: print("No brokerage connections found for the user.") else: accounts = snaptrade.connections.list_brokerage_authorization_accounts( authorization_id=connections.body[0]["id"], user_id=user_id, user_secret=user_secret, ) pprint(accounts.body) # 6) Deleting a user deleted_response = snaptrade.authentication.delete_snap_trade_user( query_params={"userId": user_id} ) pprint(deleted_response.body) ``` -------------------------------- ### Install SnapTrade Go SDK Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/go/README.md Add the SnapTrade Go SDK to your project using the go get command. ```shell go get github.com/passiv/snaptrade-sdks/sdks/go ``` -------------------------------- ### Get Return Rates Go Example Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/go/docs/ConnectionsApi.md This example demonstrates how to fetch connection rate of returns. It requires setting up the SnapTrade client with credentials and specifying the desired timeframes. ```go package main import ( "fmt" "os" snaptrade "github.com/passiv/snaptrade-sdks/sdks/go" ) func main() { configuration := snaptrade.NewConfiguration() configuration.SetPartnerClientId(os.Getenv("SNAPTRADE_CLIENT_ID")) configuration.SetConsumerKey(os.Getenv("SNAPTRADE_CONSUMER_KEY")) client := snaptrade.NewAPIClient(configuration) request := client.ConnectionsApi.ReturnRates( "userId_example", "userSecret_example", ""38400000-8cf0-11bd-b23e-10b96e4ef00d"", ) request.Timeframes("ALL,1Y") resp, httpRes, err := request.Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `ConnectionsApi.ReturnRates``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", httpRes) } // response from `ReturnRates`: RateOfReturnResponse fmt.Fprintf(os.Stdout, "Response from `ConnectionsApi.ReturnRates`: %v\n", resp) fmt.Fprintf(os.Stdout, "Response from `RateOfReturnResponse.ReturnRates.Data`: %v\n", *resp.Data) } ``` -------------------------------- ### Get Option Impact Java Example Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/java/docs/TradingApi.md Demonstrates how to initialize the Snaptrade client and call the getOptionImpact method to simulate an order. It shows how to handle successful responses and API exceptions. Includes an example using executeWithHttpInfo to get detailed response information. ```java import com.snaptrade.client.ApiClient; import com.snaptrade.client.ApiException; import com.snaptrade.client.ApiResponse; import com.snaptrade.client.Snaptrade; import com.snaptrade.client.Configuration; import com.snaptrade.client.auth.*; import com.snaptrade.client.model.*; import com.snaptrade.client.api.TradingApi; import java.util.List; import java.util.Map; import java.util.UUID; import java.math.BigDecimal; import java.util.Arrays; public class Example { public static void main(String[] args) { Configuration configuration = new Configuration(); configuration.host = "https://api.snaptrade.com/api/v1"; configuration.clientId = System.getenv("SNAPTRADE_CLIENT_ID"); configuration.consumerKey = System.getenv("SNAPTRADE_CONSUMER_KEY"); Snaptrade client = new Snaptrade(configuration); MlegOrderTypeStrict orderType = MlegOrderTypeStrict.fromValue("MARKET"); TimeInForceStrict timeInForce = TimeInForceStrict.fromValue("FOK"); List legs = Arrays.asList(); String userId = "userId_example"; String userSecret = "userSecret_example"; UUID accountId = UUID.randomUUID(); BigDecimal limitPrice = new BigDecimal(78); // The limit price. Required if the order type is `LIMIT`, `STOP_LOSS_LIMIT`. BigDecimal stopPrice = new BigDecimal(78); // The stop price. Required if the order type is `STOP_LOSS_MARKET`, `STOP_LOSS_LIMIT`. MlegPriceEffectStrictNullable priceEffect = MlegPriceEffectStrictNullable.fromValue("CREDIT"); try { OptionImpact result = client .trading .getOptionImpact(orderType, timeInForce, legs, userId, userSecret, accountId) .limitPrice(limitPrice) .stopPrice(stopPrice) .priceEffect(priceEffect) .execute(); System.out.println(result); System.out.println(result.getEstimatedCashChange()); System.out.println(result.getCashChangeDirection()); System.out.println(result.getEstimatedFeeTotal()); } catch (ApiException e) { System.err.println("Exception when calling TradingApi#getOptionImpact"); System.err.println("Status code: " + e.getStatusCode()); System.err.println("Reason: " + e.getResponseBody()); System.err.println("Response headers: " + e.getResponseHeaders()); e.printStackTrace(); } // Use .executeWithHttpInfo() to retrieve HTTP Status Code, Headers and Request try { ApiResponse response = client .trading .getOptionImpact(orderType, timeInForce, legs, userId, userSecret, accountId) .limitPrice(limitPrice) .stopPrice(stopPrice) .priceEffect(priceEffect) .executeWithHttpInfo(); System.out.println(response.getResponseBody()); System.out.println(response.getResponseHeaders()); System.out.println(response.getStatusCode()); System.out.println(response.getRoundTripTime()); System.out.println(response.getRequest()); } catch (ApiException e) { System.err.println("Exception when calling TradingApi#getOptionImpact"); System.err.println("Status code: " + e.getStatusCode()); System.err.println("Reason: " + e.getResponseBody()); System.err.println("Response headers: " + e.getResponseHeaders()); e.printStackTrace(); } } } ``` -------------------------------- ### Get Account Activities Go Example Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/go/docs/AccountInformationApi.md Demonstrates how to fetch account activities using the Go SDK. Requires setting up the API client with credentials and specifying account ID, user details, and optional date ranges, offset, limit, and activity types. ```go package main import ( "fmt" "os" "time" snaptrade "github.com/passiv/snaptrade-sdks/sdks/go" ) func main() { configuration := snaptrade.NewConfiguration() configuration.SetPartnerClientId(os.Getenv("SNAPTRADE_CLIENT_ID")) configuration.SetConsumerKey(os.Getenv("SNAPTRADE_CONSUMER_KEY")) client := snaptrade.NewAPIClient(configuration) request := client.AccountInformationApi.GetAccountActivities( ""38400000-8cf0-11bd-b23e-10b96e4ef00d"", "userId_example", "userSecret_example", ) request.StartDate(2013-10-20) request.EndDate(2013-10-20) request.Offset(56) request.Limit(56) request.Type("BUY,SELL,DIVIDEND") resp, httpRes, err := request.Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `AccountInformationApi.GetAccountActivities``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", httpRes) } // response from `GetAccountActivities`: PaginatedUniversalActivity fmt.Fprintf(os.Stdout, "Response from `AccountInformationApi.GetAccountActivities`: %v\n", resp) fmt.Fprintf(os.Stdout, "Response from `PaginatedUniversalActivity.GetAccountActivities.Data`: %v\n", *resp.Data) fmt.Fprintf(os.Stdout, "Response from `PaginatedUniversalActivity.GetAccountActivities.Pagination`: %v\n", *resp.Pagination) } ``` -------------------------------- ### Get Account Activities Example Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/csharp/README.md Demonstrates how to retrieve a list of account activities using the SnapTrade C# SDK. Ensure your SNAPTRADE_CLIENT_ID and SNAPTRADE_CONSUMER_KEY environment variables are set. ```csharp using System; using System.Collections.Generic; using System.Diagnostics; using SnapTrade.Net.Client; using SnapTrade.Net.Model; namespace Example { public class GetAccountActivitiesExample { public static void Main() { Snaptrade client = new Snaptrade(); // Configure custom BasePath if desired // client.SetBasePath("https://api.snaptrade.com/api/v1"); client.SetClientId(System.Environment.GetEnvironmentVariable("SNAPTRADE_CLIENT_ID")); client.SetConsumerKey(System.Environment.GetEnvironmentVariable("SNAPTRADE_CONSUMER_KEY")); var accountId = "accountId_example"; var userId = "userId_example"; var userSecret = "userSecret_example"; var startDate = DateTime.Parse("2013-10-20"); // 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`. (optional) var endDate = DateTime.Parse("2013-10-20"); // 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`. (optional) var offset = 56; // An integer that specifies the starting point of the paginated results. Default is 0. (optional) var limit = 56; // An integer that specifies the maximum number of transactions to return. Default of 1000. (optional) var type = "BUY,SELL,DIVIDEND"; // 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. - `TAX` - A tax related fee. - `OPTIONEXPIRATION` - Option expiration event. - `OPTIONASSIGNMENT` - Option assignment event. - `OPTIONEXERCISE` - Option exercise event. - `TRANSFER` - Transfer of assets from one account to another. - `SPLIT` - A stock share split. (optional) try { // List account activities PaginatedUniversalActivity result = client.AccountInformation.GetAccountActivities(accountId, userId, userSecret, startDate, endDate, offset, limit, type); Console.WriteLine(result); } catch (ApiException e) { Console.WriteLine("Exception when calling AccountInformationApi.GetAccountActivities: " + e.Message); Console.WriteLine("Status Code: "+ e.ErrorCode); Console.WriteLine(e.StackTrace); } catch (ClientException e) { Console.WriteLine(e.Response.StatusCode); Console.WriteLine(e.Response.RawContent); Console.WriteLine(e.InnerException); } } } } ``` -------------------------------- ### Install SnapTrade Java SDK Locally Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/java/README.md Execute this command to install the API client library to your local Maven repository. ```shell mvn clean install ``` -------------------------------- ### Get Order Impact Go Example Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/go/docs/TradingApi.md Demonstrates how to calculate the impact of a manual trade before execution. Requires setting up the API client with partner and consumer keys. ```go package main import ( "fmt" "os" snaptrade "github.com/passiv/snaptrade-sdks/sdks/go" ) func main() { configuration := snaptrade.NewConfiguration() configuration.SetPartnerClientId(os.Getenv("SNAPTRADE_CLIENT_ID")) configuration.SetConsumerKey(os.Getenv("SNAPTRADE_CONSUMER_KEY")) client := snaptrade.NewAPIClient(configuration) units := *snaptrade.Newfloat32() notionalValue := *snaptrade.NewManualTradeFormNotionalValue() manualTradeForm := *snaptrade.NewManualTradeForm( "917c8734-8470-4a3e-a18f-57c3f2ee6631", null, "2bcd7cc3-e922-4976-bce1-9858296801c3", null, null, ) manualTradeForm.SetPrice(31.33) manualTradeForm.SetStop(31.33) manualTradeForm.SetUnits(units) manualTradeForm.SetNotionalValue(notionalValue) request := client.TradingApi.GetOrderImpact( "userId_example", "userSecret_example", manualTradeForm, ) resp, httpRes, err := request.Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `TradingApi.GetOrderImpact``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", httpRes) } // response from `GetOrderImpact`: ManualTradeAndImpact fmt.Fprintf(os.Stdout, "Response from `TradingApi.GetOrderImpact`: %v\n", resp) fmt.Fprintf(os.Stdout, "Response from `ManualTradeAndImpact.GetOrderImpact.Trade`: %v\n", *resp.Trade) fmt.Fprintf(os.Stdout, "Response from `ManualTradeAndImpact.GetOrderImpact.TradeImpacts`: %v\n", *resp.TradeImpacts) fmt.Fprintf(os.Stdout, "Response from `ManualTradeAndImpact.GetOrderImpact.CombinedRemainingBalance`: %v\n", *resp.CombinedRemainingBalance) } ``` -------------------------------- ### Install SnapTrade.Net using .NET CLI Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/csharp/README.md Installs the SnapTrade.Net NuGet package using the .NET Core command-line interface. ```sh dotnet add package SnapTrade.Net ``` -------------------------------- ### Install SnapTrade.Net using NuGet CLI Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/csharp/README.md Installs the SnapTrade.Net NuGet package using the NuGet Command Line Interface. ```sh nuget install SnapTrade.Net ``` -------------------------------- ### Get Partner Info Go Example Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/go/docs/ReferenceDataApi.md Use this snippet to retrieve information about the partner, including their name, logo, and supported features. Ensure SNAPTRADE_CLIENT_ID and SNAPTRADE_CONSUMER_KEY environment variables are set. ```go package main import ( "fmt" "os" snaptrade "github.com/passiv/snaptrade-sdks/sdks/go" ) func main() { configuration := snaptrade.NewConfiguration() configuration.SetPartnerClientId(os.Getenv("SNAPTRADE_CLIENT_ID")) configuration.SetConsumerKey(os.Getenv("SNAPTRADE_CONSUMER_KEY")) client := snaptrade.NewAPIClient(configuration) request := client.ReferenceDataApi.GetPartnerInfo( ) resp, httpRes, err := request.Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `ReferenceDataApi.GetPartnerInfo``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", httpRes) } // response from `GetPartnerInfo`: PartnerData fmt.Fprintf(os.Stdout, "Response from `ReferenceDataApi.GetPartnerInfo`: %v\n", resp) fmt.Fprintf(os.Stdout, "Response from `PartnerData.GetPartnerInfo.Slug`: %v\n", *resp.Slug) fmt.Fprintf(os.Stdout, "Response from `PartnerData.GetPartnerInfo.Name`: %v\n", *resp.Name) fmt.Fprintf(os.Stdout, "Response from `PartnerData.GetPartnerInfo.LogoUrl`: %v\n", *resp.LogoUrl) fmt.Fprintf(os.Stdout, "Response from `PartnerData.GetPartnerInfo.AllowedBrokerages`: %v\n", *resp.AllowedBrokerages) fmt.Fprintf(os.Stdout, "Response from `PartnerData.GetPartnerInfo.CanAccessTrades`: %v\n", *resp.CanAccessTrades) fmt.Fprintf(os.Stdout, "Response from `PartnerData.GetPartnerInfo.CanAccessHoldings`: %v\n", *resp.CanAccessHoldings) fmt.Fprintf(os.Stdout, "Response from `PartnerData.GetPartnerInfo.CanAccessAccountHistory`: %v\n", *resp.CanAccessAccountHistory) fmt.Fprintf(os.Stdout, "Response from `PartnerData.GetPartnerInfo.CanAccessReferenceData`: %v\n", *resp.CanAccessReferenceData) fmt.Fprintf(os.Stdout, "Response from `PartnerData.GetPartnerInfo.CanAccessPortfolioManagement`: %v\n", *resp.CanAccessPortfolioManagement) fmt.Fprintf(os.Stdout, "Response from `PartnerData.GetPartnerInfo.CanAccessOrders`: %v\n", *resp.CanAccessOrders) fmt.Fprintf(os.Stdout, "Response from `PartnerData.GetPartnerInfo.RedirectUri`: %v\n", *resp.RedirectUri) fmt.Fprintf(os.Stdout, "Response from `PartnerData.GetPartnerInfo.PinRequired`: %v\n", *resp.PinRequired) } ``` -------------------------------- ### Get Order Impact with Java SDK Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/java/docs/TradingApi.md Demonstrates how to use the Java SDK to get the impact of a manual trade order. Includes setup for API client, order details, and error handling. Also shows how to retrieve detailed HTTP information. ```java import com.snaptrade.client.ApiClient; import com.snaptrade.client.ApiException; import com.snaptrade.client.ApiResponse; import com.snaptrade.client.Snaptrade; import com.snaptrade.client.Configuration; import com.snaptrade.client.auth.*; import com.snaptrade.client.model.*; import com.snaptrade.client.api.TradingApi; import java.util.List; import java.util.Map; import java.util.UUID; public class Example { public static void main(String[] args) { Configuration configuration = new Configuration(); configuration.host = "https://api.snaptrade.com/api/v1"; configuration.clientId = System.getenv("SNAPTRADE_CLIENT_ID"); configuration.consumerKey = System.getenv("SNAPTRADE_CONSUMER_KEY"); Snaptrade client = new Snaptrade(configuration); UUID accountId = UUID.randomUUID(); // Unique identifier for the connected brokerage account. This is the UUID used to reference the account in SnapTrade. ActionStrict action = ActionStrict.fromValue("BUY"); UUID universalSymbolId = UUID.randomUUID(); // Unique identifier for the symbol within SnapTrade. This is the ID used to reference the symbol in SnapTrade API calls. OrderTypeStrict orderType = OrderTypeStrict.fromValue("Limit"); TimeInForceStrict timeInForce = TimeInForceStrict.fromValue("FOK"); String userId = "userId_example"; String userSecret = "userSecret_example"; Double price = 3.4D; // The limit price for `Limit` and `StopLimit` orders. Double stop = 3.4D; // The price at which a stop order is triggered for `Stop` and `StopLimit` orders. Double units = 3.4D; // Number of shares for the order. This can be a decimal for fractional orders. Must be `null` if `notional_value` is provided. Object notionalValue = null; try { ManualTradeAndImpact result = client .trading .getOrderImpact(accountId, action, universalSymbolId, orderType, timeInForce, userId, userSecret) .price(price) .stop(stop) .units(units) .notionalValue(notionalValue) .execute(); System.out.println(result); System.out.println(result.getTrade()); System.out.println(result.getTradeImpacts()); System.out.println(result.getCombinedRemainingBalance()); } catch (ApiException e) { System.err.println("Exception when calling TradingApi#getOrderImpact"); System.err.println("Status code: " + e.getStatusCode()); System.err.println("Reason: " + e.getResponseBody()); System.err.println("Response headers: " + e.getResponseHeaders()); e.printStackTrace(); } // Use .executeWithHttpInfo() to retrieve HTTP Status Code, Headers and Request try { ApiResponse response = client .trading .getOrderImpact(accountId, action, universalSymbolId, orderType, timeInForce, userId, userSecret) .price(price) .stop(stop) .units(units) .notionalValue(notionalValue) .executeWithHttpInfo(); System.out.println(response.getResponseBody()); System.out.println(response.getResponseHeaders()); System.out.println(response.getStatusCode()); System.out.println(response.getRoundTripTime()); System.out.println(response.getRequest()); } catch (ApiException e) { System.err.println("Exception when calling TradingApi#getOrderImpact"); System.err.println("Status code: " + e.getStatusCode()); System.err.println("Reason: " + e.getResponseBody()); System.err.println("Response headers: " + e.getResponseHeaders()); e.printStackTrace(); } } } ``` -------------------------------- ### Get Session Events Go Example Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/go/docs/ConnectionsApi.md Retrieve all session events for a given user. This requires the partner client ID, user ID, and session ID. ```go package main import ( "fmt" "os" snaptrade "github.com/passiv/snaptrade-sdks/sdks/go" ) func main() { configuration := snaptrade.NewConfiguration() configuration.SetPartnerClientId(os.Getenv("SNAPTRADE_CLIENT_ID")) configuration.SetConsumerKey(os.Getenv("SNAPTRADE_CONSUMER_KEY")) client := snaptrade.NewAPIClient(configuration) request := client.ConnectionsApi.SessionEvents( "partnerClientId_example", ) request.UserId("userId_example") request.SessionId("sessionId_example") resp, httpRes, err := request.Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `ConnectionsApi.SessionEvents``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", httpRes) } // response from `SessionEvents`: []SessionEvent fmt.Fprintf(os.Stdout, "Response from `ConnectionsApi.SessionEvents`: %v\n", resp) fmt.Fprintf(os.Stdout, "Response from `SessionEvent.SessionEvents.Id`: %v\n", *resp.Id) fmt.Fprintf(os.Stdout, "Response from `SessionEvent.SessionEvents.SessionEventType`: %v\n", *resp.SessionEventType) fmt.Fprintf(os.Stdout, "Response from `SessionEvent.SessionEvents.SessionId`: %v\n", *resp.SessionId) fmt.Fprintf(os.Stdout, "Response from `SessionEvent.SessionEvents.UserId`: %v\n", *resp.UserId) fmt.Fprintf(os.Stdout, "Response from `SessionEvent.SessionEvents.CreatedDate`: %v\n", *resp.CreatedDate) fmt.Fprintf(os.Stdout, "Response from `SessionEvent.SessionEvents.BrokerageStatusCode`: %v\n", *resp.BrokerageStatusCode) fmt.Fprintf(os.Stdout, "Response from `SessionEvent.SessionEvents.BrokerageAuthorizationId`: %v\n", *resp.BrokerageAuthorizationId) } ``` -------------------------------- ### Get Security Types Go Example Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/go/docs/ReferenceDataApi.md This Go snippet retrieves a list of supported security types. It requires the SnapTrade SDK and environment variables SNAPTRADE_CLIENT_ID and SNAPTRADE_CONSUMER_KEY to be set. ```go package main import ( "fmt" "os" snaptrade "github.com/passiv/snaptrade-sdks/sdks/go" ) func main() { configuration := snaptrade.NewConfiguration() configuration.SetPartnerClientId(os.Getenv("SNAPTRADE_CLIENT_ID")) configuration.SetConsumerKey(os.Getenv("SNAPTRADE_CONSUMER_KEY")) client := snaptrade.NewAPIClient(configuration) request := client.ReferenceDataApi.GetSecurityTypes( ) resp, httpRes, err := request.Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `ReferenceDataApi.GetSecurityTypes``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", httpRes) } // response from `GetSecurityTypes`: []SecurityType fmt.Fprintf(os.Stdout, "Response from `ReferenceDataApi.GetSecurityTypes`: %v\n", resp) fmt.Fprintf(os.Stdout, "Response from `SecurityType.GetSecurityTypes.Id`: %v\n", *resp.Id) fmt.Fprintf(os.Stdout, "Response from `SecurityType.GetSecurityTypes.Code`: %v\n", *resp.Code) fmt.Fprintf(os.Stdout, "Response from `SecurityType.GetSecurityTypes.Description`: %v\n", *resp.Description) fmt.Fprintf(os.Stdout, "Response from `SecurityType.GetSecurityTypes.IsSupported`: %v\n", *resp.IsSupported) } ``` -------------------------------- ### Install Snaptrade TypeScript SDK with npm Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/typescript/README.md Install the Snaptrade TypeScript SDK using npm. ```bash npm i snaptrade-typescript-sdk ``` -------------------------------- ### Install SnapTrade.Net using Package Manager Console Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/csharp/README.md Installs the SnapTrade.Net NuGet package using the Package Manager Console in Visual Studio. ```powershell Install-Package SnapTrade.Net ``` -------------------------------- ### Get User Account Option Quotes Go Example Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/go/docs/TradingApi.md Retrieves real-time option quotes for a given symbol and account. Ensure the API client is initialized with necessary credentials. ```go package main import ( "fmt" "os" snaptrade "github.com/passiv/snaptrade-sdks/sdks/go" ) func main() { configuration := snaptrade.NewConfiguration() configuration.SetPartnerClientId(os.Getenv("SNAPTRADE_CLIENT_ID")) configuration.SetConsumerKey(os.Getenv("SNAPTRADE_CONSUMER_KEY")) client := snaptrade.NewAPIClient(configuration) request := client.TradingApi.GetUserAccountOptionQuotes( "userId_example", "userSecret_example", ""38400000-8cf0-11bd-b23e-10b96e4ef00d"", ""AAPL 251219C00150000", ) resp, httpRes, err := request.Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `TradingApi.GetUserAccountOptionQuotes``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", httpRes) } // response from `GetUserAccountOptionQuotes`: OptionQuote fmt.Fprintf(os.Stdout, "Response from `TradingApi.GetUserAccountOptionQuotes`: %v\n", resp) fmt.Fprintf(os.Stdout, "Response from `OptionQuote.GetUserAccountOptionQuotes.Symbol`: %v\n", *resp.Symbol) fmt.Fprintf(os.Stdout, "Response from `OptionQuote.GetUserAccountOptionQuotes.SyntheticPrice`: %v\n", *resp.SyntheticPrice) fmt.Fprintf(os.Stdout, "Response from `OptionQuote.GetUserAccountOptionQuotes.ImpliedVolatility`: %v\n", *resp.ImpliedVolatility) fmt.Fprintf(os.Stdout, "Response from `OptionQuote.GetUserAccountOptionQuotes.Timestamp`: %v\n", *resp.Timestamp) fmt.Fprintf(os.Stdout, "Response from `OptionQuote.GetUserAccountOptionQuotes.Greeks`: %v\n", *resp.Greeks) } ``` -------------------------------- ### Install SnapTrade Python SDK Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/python/README.md Install the SnapTrade Python SDK using pip. Ensure you are using the specified version. ```sh pip install snaptrade-python-sdk==11.0.206 ``` -------------------------------- ### Place a Force Order (Market Order Example) Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/ruby/README.md This example demonstrates placing a market order for a stock. It includes essential parameters like `account_id`, `action`, `order_type`, `time_in_force`, and `symbol`. The `units` parameter specifies the quantity to trade. ```ruby result = snaptrade.trading.place_force_order( account_id: "917c8734-8470-4a3e-a18f-57c3f2ee6631", action: "BUY", order_type: "Market", time_in_force: "Day", user_id: "snaptrade-user-123", user_secret: "adf2aa34-8219-40f7-a6b3-60156985cc61", universal_symbol_id: "2bcd7cc3-e922-4976-bce1-9858296801c3", symbol: "AAPL", trading_session: "REGULAR", expiry_date: "2026-08-21T23:27:55.027Z", price: 31.33, stop: 31.33, units: 10.5, notional_value: None, client_order_id: "550e8400-e29b-41d4-a716-446655440000" ) p result ``` -------------------------------- ### Get Symbols Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/java/docs/ReferenceDataApi.md This example demonstrates how to retrieve a list of universal symbols using the SnapTrade SDK. It shows how to initialize the client, set configuration, and make the API call, including error handling. ```APIDOC ## GET /referenceData/symbols ### Description Retrieves a list of universal symbols based on a provided query. ### Method GET ### Endpoint /referenceData/symbols ### Parameters #### Query Parameters - **substring** (string) - Optional - The search query for symbols. ### Request Example ```java // Java SDK example import com.snaptrade.client.Snaptrade; import com.snaptrade.client.Configuration; import com.snaptrade.client.model.UniversalSymbol; import java.util.List; // ... configuration setup ... Snaptrade client = new Snaptrade(configuration); String substring = "AAPL"; // Example search query try { List symbols = client.referenceData.getSymbols().substring(substring).execute(); System.out.println(symbols); } catch (Exception e) { e.printStackTrace(); } ``` ### Response #### Success Response (200) - **List** - A list of UniversalSymbol objects matching the query. #### Response Example ```json [ { "symbol": "AAPL", "symbol_id": "aapl-nyse", "exchange_id": "nyse", "name": "Apple Inc.", "asset_class": "Stocks" } ] ``` ``` -------------------------------- ### Login SnapTrade User C# Example Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/csharp/docs/AuthenticationApi.md This example demonstrates how to log in a SnapTrade user and generate a connection portal URL. Ensure your SNAPTRADE_CLIENT_ID and SNAPTRADE_CONSUMER_KEY environment variables are set. ```csharp using System; using System.Collections.Generic; using System.Diagnostics; using SnapTrade.Net.Client; using SnapTrade.Net.Model; namespace Example { public class LoginSnapTradeUserExample { public static void Main() { Snaptrade client = new Snaptrade(); // Configure custom BasePath if desired // client.SetBasePath("https://api.snaptrade.com/api/v1"); client.SetClientId(System.Environment.GetEnvironmentVariable("SNAPTRADE_CLIENT_ID")); client.SetConsumerKey(System.Environment.GetEnvironmentVariable("SNAPTRADE_CONSUMER_KEY")); var userId = "userId_example"; var userSecret = "userSecret_example"; var broker = "ALPACA"; // Slug of the brokerage to connect the user to. See [the integrations page](https://support.snaptrade.com/brokerages) for a list of supported brokerages and their slugs. var immediateRedirect = true; // 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](/docs/implement-connection-portal) for more information. var customRedirect = "https://snaptrade.com"; // 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](/docs/implement-connection-portal) for more information. var reconnect = "8b5f262d-4bb9-365d-888a-202bd3b15fa1"; // 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](/docs/fix-broken-connections) for more information. var connectionType = SnapTradeLoginUserRequestBody.ConnectionTypeEnum.Read; // Determines connection permissions (default: read) - `read`: Data access only. - `trade`: Data and trading access. - `trade-if-available`: Attempts to establish a trading connection if the brokerage supports it, otherwise falls back to read-only access automatically. var showCloseButton = true; // Controls whether the close (X) button is displayed in the connection portal. When false, you control closing behavior from your app. Defaults to true. var darkMode = true; // Enable dark mode for the connection portal. Defaults to false. var connectionPortalVersion = SnapTradeLoginUserRequestBody.ConnectionPortalVersionEnum.V4; // 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. var snapTradeLoginUserRequestBody = new SnapTradeLoginUserRequestBody( broker, immediateRedirect, customRedirect, reconnect, connectionType, showCloseButton, darkMode, connectionPortalVersion ); try { // Generate Connection Portal URL AuthenticationLoginSnapTradeUser200Response result = client.Authentication.LoginSnapTradeUser(userId, userSecret, snapTradeLoginUserRequestBody); Console.WriteLine(result); } catch (ApiException e) { Console.WriteLine("Exception when calling AuthenticationApi.LoginSnapTradeUser: " + e.Message); Console.WriteLine("Status Code: "+ e.ErrorCode); Console.WriteLine(e.StackTrace); } catch (ClientException e) { Console.WriteLine(e.Response.StatusCode); Console.WriteLine(e.Response.RawContent); Console.WriteLine(e.InnerException); } } } } ``` -------------------------------- ### Install Snaptrade TypeScript SDK with pnpm Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/typescript/README.md Install the Snaptrade TypeScript SDK using pnpm. ```bash pnpm i snaptrade-typescript-sdk ``` -------------------------------- ### Install Snaptrade TypeScript SDK with yarn Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/typescript/README.md Install the Snaptrade TypeScript SDK using yarn. ```bash yarn add snaptrade-typescript-sdk ``` -------------------------------- ### SnapTrade Python SDK Async Usage Example Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/python/README.md Demonstrates how to use the asynchronous version of the SnapTrade client to fetch account activities. This example includes error handling for API exceptions. ```python import asyncio from pprint import pprint from snaptrade_client import SnapTrade, ApiException snaptrade = SnapTrade( consumer_key="YOUR_CONSUMER_KEY", client_id="YOUR_CLIENT_ID", ) async def main(): try: # List account activities get_account_activities_response = ( await snaptrade.account_information.aget_account_activities( account_id="917c8734-8470-4a3e-a18f-57c3f2ee6631", user_id="snaptrade-user-123", user_secret="adf2aa34-8219-40f7-a6b3-60156985cc61", start_date="2022-01-24", end_date="2022-01-24", offset=0, limit=1, type="BUY,SELL,DIVIDEND", ) ) pprint(get_account_activities_response.body) pprint(get_account_activities_response.body["data"]) pprint(get_account_activities_response.body["pagination"]) pprint(get_account_activities_response.headers) pprint(get_account_activities_response.status) pprint(get_account_activities_response.round_trip_time) except ApiException as e: print( "Exception when calling AccountInformationApi.get_account_activities: %s\n" % e ) pprint(e.body) pprint(e.headers) pprint(e.status) pprint(e.reason) pprint(e.round_trip_time) asyncio.run(main()) ``` -------------------------------- ### Example HTTP Request Source: https://github.com/passiv/snaptrade-sdks/blob/master/docs/request-signatures.md An example of an HTTP POST request to the SnapTrade API, including the necessary headers and body. ```http POST /api/v1/snapTrade/registerUser?clientId=PASSIVTEST×tamp=1635790389 Signature: Content-Type: application/json {"userId":"new_user_123"} ``` -------------------------------- ### Login SnapTrade User with HttpInfo Variant C# Example Source: https://github.com/passiv/snaptrade-sdks/blob/master/sdks/csharp/docs/AuthenticationApi.md This example shows how to use the `LoginSnapTradeUserWithHttpInfo` method, which returns an `ApiResponse` object containing the response data, status code, and headers. This is useful for inspecting the full HTTP response. ```csharp try { // Generate Connection Portal URL ApiResponse response = apiInstance.LoginSnapTradeUserWithHttpInfo(userId, userSecret, snapTradeLoginUserRequestBody); Debug.Write("Status Code: " + response.StatusCode); Debug.Write("Response Headers: " + response.Headers); Debug.Write("Response Body: " + response.Data); } catch (ApiException e) { Debug.Print("Exception when calling AuthenticationApi.LoginSnapTradeUserWithHttpInfo: " + e.Message); Debug.Print("Status Code: " + e.ErrorCode); Debug.Print(e.StackTrace); } ``` -------------------------------- ### Install Expo Dependencies Source: https://github.com/passiv/snaptrade-sdks/blob/master/docs/implement-connection-portal.md Install the necessary Expo packages for web browser and deep linking functionality. These are required for handling the SnapTrade authentication flow. ```bash npx expo install expo-web-browser expo-linking ```