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

Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Csv;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpRequest;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Secrets;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        boolean success = false;

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

        Secrets vault = new Secrets();
        vault.setLocation("local_manager");
        vault.setAutoSplit(true);
        JsonObject entry = new JsonObject();
        entry.updateString("appName", "SchwabTrader");
        entry.updateString("service", "OAuth2");
        entry.updateString("username", "personal-desktop");
        JsonObject tokens = new JsonObject();
        try {
            vault.getSecretJson(entry, tokens);
        } catch (ChilkatException e) {
            System.out.println("Could not read the token record. Check the store and complete desktop authorization first.");
            return;
        }

        String accessToken = tokens.stringOf("access_token");
        if ("".equals(accessToken)) {
            System.out.println("Run the Schwab authorization or refresh example to save an access token.");
            return;
        }

        Http http = new Http();
        http.setRequireSslCertVerify(true);
        http.setAuthToken(accessToken);

        HttpResponse resp = new HttpResponse();
        HttpRequest query = new HttpRequest();
        query.setHttpVerb("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");
        try {
            http.httpReq("https://api.schwabapi.com/marketdata/v1/pricehistory", query, resp);
            success = true;
        } catch (ChilkatException e) {
            success = false;
        }
        if ((!success) || (resp.getStatusCode() != 200)) {
            if (resp.getStatusCode() == 0) {
                System.out.println("No HTTP response. Check connectivity.");
            } else {
                System.out.println("Schwab returned HTTP " + resp.getStatusCode());
                if (resp.getStatusCode() == 401) {
                    System.out.println("Refresh the access token or repeat desktop authorization.");
                }
            }

            return;
        }

        JsonObject reply = new JsonObject();
        try {
            reply.load(resp.getBodyStr());
        } catch (ChilkatException e) {
            System.out.println("Schwab returned unexpected JSON.");
            return;
        }

        int count = reply.sizeOfArray("candles");
        if (count <= 0) {
            System.out.println("No candles for this symbol and period.");
            return;
        }

        Csv csv = new Csv();
        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");
        StringBuilder millis = new StringBuilder();
        JsonObject unixTime = new JsonObject();
        DateTime candleTime = new DateTime();
        int i = 0;
        while (i < count) {
            reply.setI(i);
            String timestamp = reply.stringOf("candles[i].datetime");
            // DateOf reads Unix seconds. Drop the three millisecond digits as text.
            millis.setString(timestamp);
            int digits = millis.getLength() - 3;
            if (digits <= 0) {
                System.out.println("Missing candle timestamp.");
                return;
            }

            unixTime.updateNumber("seconds", millis.getRange(0, digits, false));
            try {
                unixTime.dateOf("seconds", candleTime);
            } catch (ChilkatException e) {
                System.out.println("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 = i + 1;
        }

        try {
            csv.saveFile2("schwab-daily-prices.csv", "utf-8");
        } catch (ChilkatException e) {
            System.out.println("Could not write schwab-daily-prices.csv.");
            return;
        }

        System.out.println("Wrote " + csv.getNumRows() + " rows to schwab-daily-prices.csv.");
    }
}