Lazarus Pascal Requires Chilkat v11.0.0+
Lazarus Pascal
Schwab: Export daily OHLCV price history
See more Schwab Examples
Downloads one year of daily open, high, low, close, and volume for one equity. The CSV records each candle’s UTC timestamp and original Unix milliseconds. Volume and prices retain their JSON number text. An empty series leaves any previous export in place.
Use the access token saved by desktop authorization. Enable the Market Data API for the Schwab app. 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.Csv,
Chilkat.CkDateTime,
Chilkat.HttpResponse,
Chilkat.HttpRequest,
Chilkat.JsonObject,
Chilkat.StringBuilder,
Chilkat.Secrets,
Chilkat.Http;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
vault: TSecrets;
entry: TJsonObject;
tokens: TJsonObject;
accessToken: string;
http: THttp;
resp: THttpResponse;
query: THttpRequest;
reply: TJsonObject;
count: Integer;
csv: TCsv;
millis: TStringBuilder;
unixTime: TJsonObject;
candleTime: TCkDateTime;
i: Integer;
timestamp: string;
digits: 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;
resp := THttpResponse.Create;
query := THttpRequest.Create;
query.HttpVerb := 'GET';
query.AddParam('symbol','AAPL');
query.AddParam('periodType','year');
query.AddParam('period','1');
query.AddParam('frequencyType','daily');
query.AddParam('frequency','1');
query.AddParam('needExtendedHoursData','false');
success := http.HttpReq('https://api.schwabapi.com/marketdata/v1/pricehistory',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;
reply := TJsonObject.Create;
success := reply.Load(resp.BodyStr);
if (success <> True) then
begin
WriteLn('Schwab returned unexpected JSON.');
Exit;
end;
count := reply.SizeOfArray('candles');
if (count <= 0) then
begin
WriteLn('No candles for this symbol and period.');
Exit;
end;
csv := TCsv.Create;
csv.SetColumnName(0,'utcTime');
csv.SetColumnName(1,'unixMilliseconds');
csv.SetColumnName(2,'open');
csv.SetColumnName(3,'high');
csv.SetColumnName(4,'low');
csv.SetColumnName(5,'close');
csv.SetColumnName(6,'volume');
millis := TStringBuilder.Create;
unixTime := TJsonObject.Create;
candleTime := TCkDateTime.Create;
i := 0;
while (i < count) do
begin
reply.I := i;
timestamp := reply.StringOf('candles[i].datetime');
// DateOf reads Unix seconds. Drop the three millisecond digits as text.
millis.SetString(timestamp);
digits := millis.Length - 3;
if (digits <= 0) then
begin
WriteLn('Missing candle timestamp.');
Exit;
end;
unixTime.UpdateNumber('seconds',millis.GetRange(0,digits,False));
success := unixTime.DateOf('seconds',candleTime);
if (success <> True) then
begin
WriteLn('Invalid candle timestamp.');
Exit;
end;
csv.SetCell(i,0,candleTime.GetAsTimestamp(False));
csv.SetCell(i,1,timestamp);
csv.SetCell(i,2,reply.StringOf('candles[i].open'));
csv.SetCell(i,3,reply.StringOf('candles[i].high'));
csv.SetCell(i,4,reply.StringOf('candles[i].low'));
csv.SetCell(i,5,reply.StringOf('candles[i].close'));
csv.SetCell(i,6,reply.StringOf('candles[i].volume'));
i := i + 1;
end;
success := csv.SaveFile2('schwab-daily-prices.csv','utf-8');
if (success <> True) then
begin
WriteLn('Could not write schwab-daily-prices.csv.');
Exit;
end;
WriteLn('Wrote ' + csv.NumRows + ' rows to schwab-daily-prices.csv.');
vault.Free;
entry.Free;
tokens.Free;
http.Free;
resp.Free;
query.Free;
reply.Free;
csv.Free;
millis.Free;
unixTime.Free;
candleTime.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.