Sample code for 30+ languages & platforms
Dart 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 Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  var success = false;

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

  final vault = CkSecrets();
  vault.location = 'local_manager';
  vault.autoSplit = true;
  final entry = CkJsonObject();
  entry.updateString('appName', 'SchwabTrader');
  entry.updateString('service', 'OAuth2');
  entry.updateString('username', 'personal-desktop');
  final tokens = CkJsonObject();
  try {
    vault.getSecretJson(entry, tokens);
  } on ChilkatException {
    print('Could not read the token record. Check the store and complete desktop authorization first.');
    return;
  }

  final accessToken = tokens.stringOf('access_token');
  if (accessToken == '') {
    print('Run the Schwab authorization or refresh example to save an access token.');
    return;
  }

  final http = CkHttp();
  http.requireSslCertVerify = true;
  http.authToken = accessToken;

  final resp = CkHttpResponse();
  final query = CkHttpRequest();
  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 = true;
  try {
    http.httpReq('https://api.schwabapi.com/marketdata/v1/pricehistory', query, resp);
  } on ChilkatException {
    success = false;
  }
  if ((!success) || (resp.statusCode != 200)) {
    if (resp.statusCode == 0) {
      print('No HTTP response. Check connectivity.');
    } else {
      print('Schwab returned HTTP ${resp.statusCode}');
      if (resp.statusCode == 401) {
        print('Refresh the access token or repeat desktop authorization.');
      }
    }

    return;
  }

  final reply = CkJsonObject();
  try {
    reply.load(resp.bodyStr);
  } on ChilkatException {
    print('Schwab returned unexpected JSON.');
    return;
  }

  final count = reply.sizeOfArray('candles');
  if (count <= 0) {
    print('No candles for this symbol and period.');
    return;
  }

  final csv = CkCsv();
  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');
  final millis = CkStringBuilder();
  final unixTime = CkJsonObject();
  final candleTime = CkDateTime();
  var i = 0;
  while (i < count) {
    reply.i = i;
    final timestamp = reply.stringOf('candles[i].datetime');
    // DateOf reads Unix seconds. Drop the three millisecond digits as text.
    millis.setString(timestamp);
    final digits = millis.length - 3;
    if (digits <= 0) {
      print('Missing candle timestamp.');
      return;
    }

    unixTime.updateNumber('seconds', millis.getRange(0, digits, false));
    try {
      unixTime.dateOf('seconds', candleTime);
    } on ChilkatException {
      print('Invalid candle timestamp.');
      return;
    }

    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++;
  }

  try {
    csv.saveFile2('schwab-daily-prices.csv', 'utf-8');
  } on ChilkatException {
    print('Could not write schwab-daily-prices.csv.');
    return;
  }

  print('Wrote ${csv.numRows} rows to schwab-daily-prices.csv.');
}