Sample code for 30+ languages & platforms
Lazarus Pascal 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 Lazarus Pascal Downloads

Lazarus Pascal
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Csv,
  Chilkat.CkDateTime,
  Chilkat.JsonArray,
  Chilkat.HttpRequest,
  Chilkat.HttpResponse,
  Chilkat.StringBuilder,
  Chilkat.JsonObject,
  Chilkat.Secrets,
  Chilkat.Http;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  vault: TSecrets;
  entry: TJsonObject;
  tokens: TJsonObject;
  accessToken: string;
  http: THttp;
  selection: TJsonObject;
  accountHash: string;
  clock: TCkDateTime;
  endTime: TStringBuilder;
  replacements: Integer;
  startTime: TStringBuilder;
  resp: THttpResponse;
  query: THttpRequest;
  activity: TJsonArray;
  csv: TCsv;
  row: TJsonObject;
  i: Integer;

begin
  success := False;

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

  vault := TSecrets.Create;
  vault.Location := 'local_manager';
  vault.AutoSplit := True;
  entry := TJsonObject.Create;
  entry.UpdateString('appName','SchwabTrader');
  entry.UpdateString('service','OAuth2');
  entry.UpdateString('username','personal-desktop');
  tokens := TJsonObject.Create;
  success := vault.GetSecretJson(entry,tokens);
  if (success <> True) then
    begin
      WriteLn('Could not read the token record. Check the store and complete desktop authorization first.');
      Exit;
    end;
  accessToken := tokens.StringOf('access_token');
  if (accessToken = '') then
    begin
      WriteLn('Run the Schwab authorization or refresh example to save an access token.');
      Exit;
    end;
  http := THttp.Create;
  http.RequireSslCertVerify := True;
  http.AuthToken := accessToken;

  //  Read the hash saved by the authorized-account selection example.
  entry.UpdateString('service','SelectedAccount');
  selection := TJsonObject.Create;
  success := vault.GetSecretJson(entry,selection);
  accountHash := selection.StringOf('hashValue');
  if ((success <> True) or (accountHash = '')) then
    begin
      WriteLn('Select an authorized account first.');
      Exit;
    end;
  http.SetUrlVar('account',accountHash);

  //  Use UTC endpoints for a rolling seven-day window.
  clock := TCkDateTime.Create;
  clock.SetFromCurrentSystemTime();
  endTime := TStringBuilder.Create;
  endTime.Append(clock.GetAsTimestamp(False));
  replacements := endTime.Replace('Z','.000Z');
  clock.AddDays(-7);
  startTime := TStringBuilder.Create;
  startTime.Append(clock.GetAsTimestamp(False));
  replacements := startTime.Replace('Z','.000Z');
  resp := THttpResponse.Create;
  query := THttpRequest.Create;
  query.HttpVerb := 'GET';
  query.AddParam('startDate',startTime.GetAsString());
  query.AddParam('endDate',endTime.GetAsString());
  query.AddParam('types','TRADE,DIVIDEND_OR_INTEREST');
  success := http.HttpReq('https://api.schwabapi.com/trader/v1/accounts/{$account}/transactions',query,resp);
  if ((success <> True) or (resp.StatusCode <> 200)) then
    begin
      if (resp.StatusCode = 0) then
        begin
          WriteLn('No HTTP response. Check connectivity.');
        end
      else
        begin
          WriteLn('Schwab returned HTTP ' + resp.StatusCode);
          if (resp.StatusCode = 401) then
            begin
              WriteLn('Refresh the access token or repeat desktop authorization.');
            end;
        end;
      Exit;
    end;
  activity := TJsonArray.Create;
  success := activity.Load(resp.BodyStr);
  if (success <> True) then
    begin
      WriteLn('Schwab returned unexpected JSON.');
      Exit;
    end;

  if (activity.Size >= 3000) then
    begin
      WriteLn('The response reached the transaction limit. Export smaller time windows.');
      Exit;
    end;
  csv := TCsv.Create;
  csv.SetColumnName(0,'activityId');
  csv.SetColumnName(1,'time');
  csv.SetColumnName(2,'type');
  csv.SetColumnName(3,'tradeDate');
  csv.SetColumnName(4,'settlementDate');
  csv.SetColumnName(5,'netAmount');
  row := TJsonObject.Create;
  i := 0;
  while (i < activity.Size) do
    begin
      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 := i + 1;
    end;

  success := csv.SaveFile2('schwab-transactions.csv','utf-8');
  if (success <> True) then
    begin
      WriteLn('Could not write schwab-transactions.csv.');
      Exit;
    end;
  WriteLn('Wrote ' + csv.NumRows + ' rows to schwab-transactions.csv.');


  vault.Free;
  entry.Free;
  tokens.Free;
  http.Free;
  selection.Free;
  clock.Free;
  endTime.Free;
  startTime.Free;
  resp.Free;
  query.Free;
  activity.Free;
  csv.Free;
  row.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.