Lazarus Pascal Requires Chilkat v11.0.0+
Lazarus Pascal
Schwab: Preview a single-leg equity limit order
See more Schwab Examples
Builds a day limit order for one share and posts it to previewOrder. Reads the projected order and the validation messages, including warnings and rejection reasons. A successful HTTP response means the preview completed. A preview does not submit an order, reserve buying power, or guarantee later acceptance.
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.
Chilkat Lazarus Pascal Downloads
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.JsonArray,
Chilkat.HttpResponse,
Chilkat.JsonObject;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
vault: TSecrets;
entry: TJsonObject;
tokens: TJsonObject;
accessToken: string;
http: THttp;
selection: TJsonObject;
accountHash: string;
order: TJsonObject;
resp: THttpResponse;
reply: TJsonObject;
validation: TJsonObject;
rules: TJsonArray;
detail: TJsonObject;
messages: Integer;
i: Integer;
category: string;
j: 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);
// These are illustrative preview inputs. Set the symbol, quantity and limit price.
order := TJsonObject.Create;
// The PreviewOrder schema puts orderLegs inside orderStrategy.
order.UpdateString('orderStrategy.session','NORMAL');
order.UpdateString('orderStrategy.duration','DAY');
order.UpdateString('orderStrategy.orderType','LIMIT');
order.UpdateString('orderStrategy.orderStrategyType','SINGLE');
order.UpdateNumber('orderStrategy.price','100.00');
order.UpdateInt('orderStrategy.quantity',1);
order.UpdateString('orderStrategy.orderLegs[0].instruction','BUY');
order.UpdateInt('orderStrategy.orderLegs[0].quantity',1);
order.UpdateString('orderStrategy.orderLegs[0].finalSymbol','AAPL');
order.UpdateString('orderStrategy.orderLegs[0].assetType','EQUITY');
resp := THttpResponse.Create;
success := http.HttpJson('POST','https://api.schwabapi.com/trader/v1/accounts/{$account}/previewOrder',order,'application/json',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;
reply := TJsonObject.Create;
success := reply.Load(resp.BodyStr);
if (success <> True) then
begin
WriteLn('Schwab returned unexpected JSON.');
Exit;
end;
WriteLn('Preview only. No order was submitted.');
if (reply.HasMember('orderStrategy.orderType') = True) then
begin
WriteLn('Projected order: ' + reply.StringOf('orderStrategy.orderType') + ' price ' + reply.StringOf('orderStrategy.price'));
end;
if (reply.HasMember('orderStrategy.orderBalance.projectedBuyingPower') = True) then
begin
WriteLn('Projected buying power: ' + reply.StringOf('orderStrategy.orderBalance.projectedBuyingPower'));
end;
validation := TJsonObject.Create;
success := reply.ObjectOf2('orderValidationResult',validation);
if (success <> True) then
begin
WriteLn('Schwab supplied no validation result.');
Exit;
end;
// Each category (accepts, alerts, warns, reviews, rejects) contains rule messages.
rules := TJsonArray.Create;
detail := TJsonObject.Create;
messages := 0;
i := 0;
while (i < validation.Size) do
begin
category := validation.NameAt(i);
success := validation.ArrayAt2(i,rules);
if (success = True) then
begin
j := 0;
while (j < rules.Size) do
begin
rules.ObjectAt2(j,detail);
WriteLn(category + ' ' + detail.StringOf('validationRuleName') + ' ' + detail.StringOf('message') + ' ' + detail.StringOf('activityMessage'));
messages := messages + 1;
j := j + 1;
end;
end;
i := i + 1;
end;
if (messages = 0) then
begin
WriteLn('No validation messages returned.');
end;
vault.Free;
entry.Free;
tokens.Free;
http.Free;
selection.Free;
order.Free;
resp.Free;
reply.Free;
validation.Free;
rules.Free;
detail.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.