Sample code for 30+ languages & platforms
Dart Requires Chilkat v11.0.0+

Schwab: Export account transactions to CSV

See more Schwab Examples

Exports the last seven days of trades, dividends, and interest for one account. Each UTF-8 CSV row represents an activity, including its signed net amount. The file is replaced on each run. For incremental imports, key records by account and activityId so overlapping date windows do not duplicate entries. If a window returns the 3,000-transaction maximum, split it before treating it as complete.

Use the access token saved by desktop authorization. First select the authorized account whose data you want to use. Use the same Chilkat Secrets store as the OAuth example.

Schwab API specification

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  var success = false;

  // Assumes Chilkat is unlocked. See Global Unlock Sample.
  success = false;

  final vault = CkSecrets();
  vault.location = 'local_manager';
  vault.autoSplit = true;
  final entry = CkJsonObject();
  entry.updateString('appName', 'SchwabTrader');
  entry.updateString('service', 'OAuth2');
  entry.updateString('username', 'personal-desktop');
  final tokens = CkJsonObject();
  try {
    vault.getSecretJson(entry, tokens);
  } on ChilkatException {
    print('Could not read the token record. Check the store and complete desktop authorization first.');
    return;
  }

  final accessToken = tokens.stringOf('access_token');
  if (accessToken == '') {
    print('Run the Schwab authorization or refresh example to save an access token.');
    return;
  }

  final http = CkHttp();
  http.requireSslCertVerify = true;
  http.authToken = accessToken;

  // Read the hash saved by the authorized-account selection example.
  entry.updateString('service', 'SelectedAccount');
  final selection = CkJsonObject();
  success = true;
  try {
    vault.getSecretJson(entry, selection);
  } on ChilkatException {
    success = false;
  }
  final accountHash = selection.stringOf('hashValue');
  if ((!success) || (accountHash == '')) {
    print('Select an authorized account first.');
    return;
  }

  http.setUrlVar('account', accountHash);

  // Use UTC endpoints for a rolling seven-day window.
  final clock = CkDateTime();
  clock.setFromCurrentSystemTime();
  final endTime = CkStringBuilder();
  endTime.append(clock.getAsTimestamp(false));
  var replacements = endTime.replace('Z', '.000Z');
  clock.addDays(-7);
  final startTime = CkStringBuilder();
  startTime.append(clock.getAsTimestamp(false));
  replacements = startTime.replace('Z', '.000Z');
  final resp = CkHttpResponse();
  final query = CkHttpRequest();
  query.httpVerb = 'GET';
  query.addParam('startDate', startTime.getAsString());
  query.addParam('endDate', endTime.getAsString());
  query.addParam('types', 'TRADE,DIVIDEND_OR_INTEREST');
  success = true;
  try {
    http.httpReq('https://api.schwabapi.com/trader/v1/accounts/{\$account}/transactions', query, resp);
  } on ChilkatException {
    success = false;
  }
  if ((!success) || (resp.statusCode != 200)) {
    if (resp.statusCode == 0) {
      print('No HTTP response. Check connectivity.');
    } else {
      print('Schwab returned HTTP ${resp.statusCode}');
      if (resp.statusCode == 401) {
        print('Refresh the access token or repeat desktop authorization.');
      }
    }

    return;
  }

  final activity = CkJsonArray();
  try {
    activity.load(resp.bodyStr);
  } on ChilkatException {
    print('Schwab returned unexpected JSON.');
    return;
  }

  if (activity.size >= 3000) {
    print('The response reached the transaction limit. Export smaller time windows.');
    return;
  }

  final csv = CkCsv();
  csv.setColumnName(0, 'activityId');
  csv.setColumnName(1, 'time');
  csv.setColumnName(2, 'type');
  csv.setColumnName(3, 'tradeDate');
  csv.setColumnName(4, 'settlementDate');
  csv.setColumnName(5, 'netAmount');
  final row = CkJsonObject();
  var i = 0;
  while (i < activity.size) {
    activity.objectAt2(i, row);
    // Keep identifiers and decimal amounts as returned by Schwab.
    csv.setCell(i, 0, row.stringOf('activityId'));
    csv.setCell(i, 1, row.stringOf('time'));
    csv.setCell(i, 2, row.stringOf('type'));
    csv.setCell(i, 3, row.stringOf('tradeDate'));
    csv.setCell(i, 4, row.stringOf('settlementDate'));
    csv.setCell(i, 5, row.stringOf('netAmount'));
    i++;
  }

  try {
    csv.saveFile2('schwab-transactions.csv', 'utf-8');
  } on ChilkatException {
    print('Could not write schwab-transactions.csv.');
    return;
  }

  print('Wrote ${csv.numRows} rows to schwab-transactions.csv.');
}