Sample code for 30+ languages & platforms
Delphi DLL Requires Chilkat v11.0.0+

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.

Schwab API specification

Chilkat Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
vault: HCkSecrets;
entry: HCkJsonObject;
tokens: HCkJsonObject;
accessToken: PWideChar;
http: HCkHttp;
resp: HCkHttpResponse;
query: HCkHttpRequest;
reply: HCkJsonObject;
count: Integer;
csv: HCkCsv;
millis: HCkStringBuilder;
unixTime: HCkJsonObject;
candleTime: HCkDateTime;
i: Integer;
timestamp: PWideChar;
digits: Integer;

begin
success := False;

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

vault := CkSecrets_Create();
CkSecrets_putLocation(vault,'local_manager');
CkSecrets_putAutoSplit(vault,True);
entry := CkJsonObject_Create();
CkJsonObject_UpdateString(entry,'appName','SchwabTrader');
CkJsonObject_UpdateString(entry,'service','OAuth2');
CkJsonObject_UpdateString(entry,'username','personal-desktop');
tokens := CkJsonObject_Create();
success := CkSecrets_GetSecretJson(vault,entry,tokens);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not read the token record. Check the store and complete desktop authorization first.');
    Exit;
  end;
accessToken := CkJsonObject__stringOf(tokens,'access_token');
if (accessToken = '') then
  begin
    Memo1.Lines.Add('Run the Schwab authorization or refresh example to save an access token.');
    Exit;
  end;
http := CkHttp_Create();
CkHttp_putRequireSslCertVerify(http,True);
CkHttp_putAuthToken(http,accessToken);

resp := CkHttpResponse_Create();
query := CkHttpRequest_Create();
CkHttpRequest_putHttpVerb(query,'GET');
CkHttpRequest_AddParam(query,'symbol','AAPL');
CkHttpRequest_AddParam(query,'periodType','year');
CkHttpRequest_AddParam(query,'period','1');
CkHttpRequest_AddParam(query,'frequencyType','daily');
CkHttpRequest_AddParam(query,'frequency','1');
CkHttpRequest_AddParam(query,'needExtendedHoursData','false');
success := CkHttp_HttpReq(http,'https://api.schwabapi.com/marketdata/v1/pricehistory',query,resp);
if ((success <> True) or (CkHttpResponse_getStatusCode(resp) <> 200)) then
  begin
    if (CkHttpResponse_getStatusCode(resp) = 0) then
      begin
        Memo1.Lines.Add('No HTTP response. Check connectivity.');
      end
    else
      begin
        Memo1.Lines.Add('Schwab returned HTTP ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
        if (CkHttpResponse_getStatusCode(resp) = 401) then
          begin
            Memo1.Lines.Add('Refresh the access token or repeat desktop authorization.');
          end;
      end;
    Exit;
  end;
reply := CkJsonObject_Create();
success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
if (success <> True) then
  begin
    Memo1.Lines.Add('Schwab returned unexpected JSON.');
    Exit;
  end;

count := CkJsonObject_SizeOfArray(reply,'candles');
if (count <= 0) then
  begin
    Memo1.Lines.Add('No candles for this symbol and period.');
    Exit;
  end;
csv := CkCsv_Create();
CkCsv_SetColumnName(csv,0,'utcTime');
CkCsv_SetColumnName(csv,1,'unixMilliseconds');
CkCsv_SetColumnName(csv,2,'open');
CkCsv_SetColumnName(csv,3,'high');
CkCsv_SetColumnName(csv,4,'low');
CkCsv_SetColumnName(csv,5,'close');
CkCsv_SetColumnName(csv,6,'volume');
millis := CkStringBuilder_Create();
unixTime := CkJsonObject_Create();
candleTime := CkDateTime_Create();
i := 0;
while (i < count) do
  begin
    CkJsonObject_putI(reply,i);
    timestamp := CkJsonObject__stringOf(reply,'candles[i].datetime');
    //  DateOf reads Unix seconds. Drop the three millisecond digits as text.
    CkStringBuilder_SetString(millis,timestamp);
    digits := CkStringBuilder_getLength(millis) - 3;
    if (digits <= 0) then
      begin
        Memo1.Lines.Add('Missing candle timestamp.');
        Exit;
      end;
    CkJsonObject_UpdateNumber(unixTime,'seconds',CkStringBuilder__getRange(millis,0,digits,False));
    success := CkJsonObject_DateOf(unixTime,'seconds',candleTime);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Invalid candle timestamp.');
        Exit;
      end;
    CkCsv_SetCell(csv,i,0,CkDateTime__getAsTimestamp(candleTime,False));
    CkCsv_SetCell(csv,i,1,timestamp);
    CkCsv_SetCell(csv,i,2,CkJsonObject__stringOf(reply,'candles[i].open'));
    CkCsv_SetCell(csv,i,3,CkJsonObject__stringOf(reply,'candles[i].high'));
    CkCsv_SetCell(csv,i,4,CkJsonObject__stringOf(reply,'candles[i].low'));
    CkCsv_SetCell(csv,i,5,CkJsonObject__stringOf(reply,'candles[i].close'));
    CkCsv_SetCell(csv,i,6,CkJsonObject__stringOf(reply,'candles[i].volume'));
    i := i + 1;
  end;

success := CkCsv_SaveFile2(csv,'schwab-daily-prices.csv','utf-8');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not write schwab-daily-prices.csv.');
    Exit;
  end;
Memo1.Lines.Add('Wrote ' + IntToStr(CkCsv_getNumRows(csv)) + ' rows to schwab-daily-prices.csv.');

CkSecrets_Dispose(vault);
CkJsonObject_Dispose(entry);
CkJsonObject_Dispose(tokens);
CkHttp_Dispose(http);
CkHttpResponse_Dispose(resp);
CkHttpRequest_Dispose(query);
CkJsonObject_Dispose(reply);
CkCsv_Dispose(csv);
CkStringBuilder_Dispose(millis);
CkJsonObject_Dispose(unixTime);
CkDateTime_Dispose(candleTime);