-
Notifications
You must be signed in to change notification settings - Fork 1
Home
Greg Porter edited this page Aug 26, 2024
·
9 revisions
- Create a developer account and app at the Schwab Developer Portal. See User Registration for help creating an account and Create an App for help with app creation. You will need the Client Id/App Key, Client Secret and redirect URL(s) from the app in subsequent steps. Important: in order for the service to successfully generate refresh tokens, redirect URIs should use this format and path:
https://<YOUR-BASE-URL>/oauth2/schwab/code
.
- Create or use an existing spring boot project. See the Spring Quickstart for help setting up a project.
- If you are using Maven, include the schwab-api-client as a dependency in your pom.xml
<dependency>
<groupId>com.pangility</groupId>
<artifactId>schwab-api-client</artifactId>
<version>0.1.5</version>
</dependency>
- Copy /src/main/resources/schwabapiclient.properties into the resources directory of your project. This file contains all the property data that the library needs to successfully communicate with the Schwab API.
- Add the following entries into your application.yml substituting the information you gathered from step 1:
schwab-api:
oauth2:
clientId: <YOUR-SCHWAB-CLIENT-ID>
clientSecret: <YOUR-SCHWAB-CLIENT-SECRET>
redirect-uri: <YOUR-SCHWAB-REDIRECT-URI>
- Create a class that implements the SchwabTokenHandler interface and override the onAccessTokenChange and onRefreshTokenChange methods. These methods will be triggered when SchwabOauth2Controller updates the tokens. You'll want to save the refresh token from onRefreshTokenChange for your app to use in the future. The refresh token will expire every 7 days and can be used to generate access tokens until then. The Access token expires in 30 minutes and will be refreshed automatically by the library as long as there is a valid refresh token.
public class ClientTokenHandler implements SchwabTokenHandler {
@Override
public void onAccessTokenChange(@NotNull SchwabAccount schwabAccount) {
// ...Do something with the Access Token here
}
@Override
public void onRefreshTokenChange(@NotNull SchwabAccount schwabAccount) {
// ...Do something to save the Refresh Token here
System.out.print(schwabAccount.getRefreshToken());
System.out.print(" expires on ");
System.out.println(schwabAccount.getRefreshExpiration());
}
}
- Create a class that will be consuming the API. Annotate it with @EnableSchwabApi, @EnableSchwabAccountsAndTradingApi or @EnableSchwabMarketDataApi to enable the API client controller(s) for use in the class. @Autowire the client controller of the API that you have enabled. SchwabAccountsAndTradingApiClient for the Schwab Accounts and Trading API and SchwabMarketDataApiClient for the Schwab Market Data API
@Service
@EnableSchwabMarketDataApi
public class SchwabApiClientHandler {
@Autowired
private SchwabMarketDataApiClient schwabMarketDataApiClient;
- Initialize the API client service with a single or a list of SchwabAccount along with (optionally) an instance of your token handler from step 6. You can pass the refresh and access tokens to the service, if you have them, or you can have the library generate them for you (see step 9).
ClientTokenHandler clientTokenHandler = new ClientTokenHandler();
SchwabAccount schwabAccount = new SchwabAccount();
schwabAccount.setUserId(schwabUserId);
// If you have saved your refresh token, pass it to the API client service.
// schwabAccount.setRefreshToken(schwabRefreshToken);
// schwabAccount.setRefreshExpiration(schwabRefreshExpiration);
schwabMarketDataApiClient.init(schwabAccount, clientTokenHandler);
- To initialize and/or refresh an expired refresh token, call the rest service included in the library at
https://<YOUR-BASE-URL>/oauth2/schwab/authorization?schwabUserId=<YOUR-SCHWAB-USERID>&callback=<SOME-URL>
from a browser or a web application. The service will use the Schwab client id/app key, client secret and redirect URI defined in step 5. You'll also need to pass it the Schwab user id that you just used to initialize the Schwab API client service. The callback query parameter tells it where to redirect after a refresh token is successfully generated. The onRefreshTokenChange method from your Token Handler will be triggered so that you can save the refresh token for future access token generation.
- Call the API! You are now ready to call the API. Each API client service contains fetch methods that correspond with the endpoints of the Schwab API. Some will use ...Request objects to pass parameters. Others that are less complicated will accept the parameters directly in the call to the method. See the schwab-api-client javadocs and Schwab API documentation for more details. For example, get a market quote for SPY:
schwabMarketDataApiClient.fetchQuoteToMono("SPY")
.flatMap(quoteResponse -> // do something with the quote)
.onErrorResume(SymbolNotFoundException.class, e -> // handle the exception)
.subscribe();
or get the movers on the NYSE with a ...Request object:
MoversRequest moversRequest = MoversRequest.builder()
.withIndexSymbol(MoversRequest.IndexSymbol.NYSE)
.build();
schwabMarketDataApiClient.fetchMoversToFlux(moversRequest)
.flatMap(screener -> // do something with the response)
.onErrorResume(SymbolNotFoundException.class, e -> // handle the exception)
.subscribe();
See Schwab API Client Example for a working example project.