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

Schwab: List recent orders for one account

See more Schwab Examples

Lists orders entered in the last seven days, with an optional status filter such as WORKING. Shows the order ID, entry time, status, filled quantity, and remaining quantity. Select an ID from the results for the order detail and fills example. An older order can still be working outside this entry-time window.

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.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;
  statusFilter: string;
  resp: THttpResponse;
  query: THttpRequest;
  orders: TJsonArray;
  order: 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');
  statusFilter := '';
  resp := THttpResponse.Create;
  query := THttpRequest.Create;
  query.HttpVerb := 'GET';
  query.AddParam('fromEnteredTime',startTime.GetAsString());
  query.AddParam('toEnteredTime',endTime.GetAsString());
  query.AddParam('maxResults','100');
  if (statusFilter <> '') then
    begin
      query.AddParam('status',statusFilter);
    end;
  success := http.HttpReq('https://api.schwabapi.com/trader/v1/accounts/{$account}/orders',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;
  orders := TJsonArray.Create;
  success := orders.Load(resp.BodyStr);
  if (success <> True) then
    begin
      WriteLn('Schwab returned unexpected JSON.');
      Exit;
    end;

  if (orders.Size = 0) then
    begin
      WriteLn('No matching orders entered during this interval.');
    end;
  if (orders.Size = 100) then
    begin
      WriteLn('Reached maxResults. Narrow the interval to check for additional orders.');
    end;
  order := TJsonObject.Create;
  i := 0;
  while (i < orders.Size) do
    begin
      orders.ObjectAt2(i,order);
      WriteLn('Order ' + order.StringOf('orderId') + '  ' + order.StringOf('enteredTime') + '  ' + order.StringOf('orderType') + '  ' + order.StringOf('status'));
      WriteLn('  filled ' + order.StringOf('filledQuantity') + '  remaining ' + order.StringOf('remainingQuantity'));
      i := i + 1;
    end;



  vault.Free;
  entry.Free;
  tokens.Free;
  http.Free;
  selection.Free;
  clock.Free;
  endTime.Free;
  startTime.Free;
  resp.Free;
  query.Free;
  orders.Free;
  order.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.