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

Schwab: Inspect an order, its legs, and fills

See more Schwab Examples

Use an order ID from the selected account’s recent orders. The example reads a single order and matches executions to order legs by legId. Each execution can have its own quantity, price, and timestamp. Working orders can have zero or partial fills. The loops cover the returned order’s own legs and activities.

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.Http,
  Chilkat.Secrets,
  Chilkat.HttpResponse,
  Chilkat.JsonObject;

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

procedure RunDemo;
var
  success: Boolean;
  vault: TSecrets;
  entry: TJsonObject;
  tokens: TJsonObject;
  accessToken: string;
  http: THttp;
  selection: TJsonObject;
  accountHash: string;
  orderId: string;
  resp: THttpResponse;
  order: TJsonObject;
  symbols: TJsonObject;
  i: Integer;
  legId: string;
  symbol: string;
  fills: Integer;
  j: Integer;
  filledLeg: string;

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);

  //  Supply the ID as text so large numeric identifiers keep all their digits.
  orderId := 'ORDER_ID_FROM_LIST';
  http.SetUrlVar('orderId',orderId);
  resp := THttpResponse.Create;
  success := http.HttpNoBody('GET','https://api.schwabapi.com/trader/v1/accounts/{$account}/orders/{$orderId}',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;
  order := TJsonObject.Create;
  success := order.Load(resp.BodyStr);
  if (success <> True) then
    begin
      WriteLn('Schwab returned unexpected JSON.');
      Exit;
    end;

  WriteLn('Order ' + order.StringOf('orderId') + '  ' + order.StringOf('status'));
  symbols := TJsonObject.Create;
  i := 0;
  while (i < order.SizeOfArray('orderLegCollection')) do
    begin
      order.I := i;
      legId := order.StringOf('orderLegCollection[i].legId');
      symbol := order.StringOf('orderLegCollection[i].instrument.symbol');
      symbols.UpdateString(legId,symbol);
      WriteLn('Leg ' + legId + '  ' + order.StringOf('orderLegCollection[i].instruction') + ' ' + order.StringOf('orderLegCollection[i].quantity') + ' ' + symbol);
      i := i + 1;
    end;

  fills := 0;
  i := 0;
  while (i < order.SizeOfArray('orderActivityCollection')) do
    begin
      order.I := i;
      if (order.StringOfEquals('orderActivityCollection[i].executionType','FILL',True) = True) then
        begin
          j := 0;
          while (j < order.SizeOfArray('orderActivityCollection[i].executionLegs')) do
            begin
              order.J := j;
              filledLeg := order.StringOf('orderActivityCollection[i].executionLegs[j].legId');
              WriteLn('Fill on leg ' + filledLeg + '  ' + symbols.StringOf(filledLeg) + '  quantity ' + order.StringOf('orderActivityCollection[i].executionLegs[j].quantity')
                   + '  price ' + order.StringOf('orderActivityCollection[i].executionLegs[j].price') + '  time ' + order.StringOf('orderActivityCollection[i].executionLegs[j].time'));
              fills := fills + 1;
              j := j + 1;
            end;

        end;
      i := i + 1;
    end;

  if (fills = 0) then
    begin
      WriteLn('No fills reported for this order.');
    end;


  vault.Free;
  entry.Free;
  tokens.Free;
  http.Free;
  selection.Free;
  resp.Free;
  order.Free;
  symbols.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.