Swift Requires Chilkat v11.0.0+
Swift
Schwab: Export account transactions to CSV
See more Schwab Examples
Exports the last seven days of trades, dividends, and interest for one account. Each UTF-8 CSV row represents an activity, including its signed net amount. The file is replaced on each run. For incremental imports, key records by account and activityId so overlapping date windows do not duplicate entries. If a window returns the 3,000-transaction maximum, split it before treating it as complete.
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 Swift Downloads
func chilkatTest() {
var success: Bool = false
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false
let vault = CkoSecrets()!
vault.location = "local_manager"
vault.autoSplit = true
let entry = CkoJsonObject()!
entry.updateString(jsonPath: "appName", value: "SchwabTrader")
entry.updateString(jsonPath: "service", value: "OAuth2")
entry.updateString(jsonPath: "username", value: "personal-desktop")
let tokens = CkoJsonObject()!
success = vault.getSecretJson(jsonId: entry, jsonOut: tokens)
if success != true {
print("Could not read the token record. Check the store and complete desktop authorization first.")
return
}
var accessToken: String? = tokens.string(of: "access_token")
if accessToken == "" {
print("Run the Schwab authorization or refresh example to save an access token.")
return
}
let http = CkoHttp()!
http.requireSslCertVerify = true
http.authToken = accessToken
// Read the hash saved by the authorized-account selection example.
entry.updateString(jsonPath: "service", value: "SelectedAccount")
let selection = CkoJsonObject()!
success = vault.getSecretJson(jsonId: entry, jsonOut: selection)
var accountHash: String? = selection.string(of: "hashValue")
if (success != true) || (accountHash == "") {
print("Select an authorized account first.")
return
}
http.setUrlVar(name: "account", value: accountHash)
// Use UTC endpoints for a rolling seven-day window.
let clock = CkoDateTime()!
clock.setFromCurrentSystemTime()
let endTime = CkoStringBuilder()!
endTime.append(value: clock.get(asTimestamp: false))
var replacements: Int = endTime.replace(value: "Z", replacement: ".000Z").intValue
clock.addDays(numDays: -7)
let startTime = CkoStringBuilder()!
startTime.append(value: clock.get(asTimestamp: false))
replacements = startTime.replace(value: "Z", replacement: ".000Z").intValue
let resp = CkoHttpResponse()!
let query = CkoHttpRequest()!
query.httpVerb = "GET"
query.addParam(name: "startDate", value: startTime.getAsString())
query.addParam(name: "endDate", value: endTime.getAsString())
query.addParam(name: "types", value: "TRADE,DIVIDEND_OR_INTEREST")
success = http.httpReq(url: "https://api.schwabapi.com/trader/v1/accounts/{$account}/transactions", request: query, response: resp)
if (success != true) || (resp.statusCode.intValue != 200) {
if resp.statusCode.intValue == 0 {
print("No HTTP response. Check connectivity.")
}
else {
print("Schwab returned HTTP \(resp.statusCode.intValue)")
if resp.statusCode.intValue == 401 {
print("Refresh the access token or repeat desktop authorization.")
}
}
return
}
let activity = CkoJsonArray()!
success = activity.load(jsonArray: resp.bodyStr)
if success != true {
print("Schwab returned unexpected JSON.")
return
}
if activity.size.intValue >= 3000 {
print("The response reached the transaction limit. Export smaller time windows.")
return
}
let csv = CkoCsv()!
csv.setColumnName(index: 0, columnName: "activityId")
csv.setColumnName(index: 1, columnName: "time")
csv.setColumnName(index: 2, columnName: "type")
csv.setColumnName(index: 3, columnName: "tradeDate")
csv.setColumnName(index: 4, columnName: "settlementDate")
csv.setColumnName(index: 5, columnName: "netAmount")
let row = CkoJsonObject()!
var i: Int = 0
while (i < activity.size.intValue) {
activity.objectAt2(index: i, jsonObj: row)
// Keep identifiers and decimal amounts as returned by Schwab.
csv.setCell(row: i, col: 0, content: row.string(of: "activityId"))
csv.setCell(row: i, col: 1, content: row.string(of: "time"))
csv.setCell(row: i, col: 2, content: row.string(of: "type"))
csv.setCell(row: i, col: 3, content: row.string(of: "tradeDate"))
csv.setCell(row: i, col: 4, content: row.string(of: "settlementDate"))
csv.setCell(row: i, col: 5, content: row.string(of: "netAmount"))
i = i + 1
}
success = csv.saveFile2(path: "schwab-transactions.csv", charset: "utf-8")
if success != true {
print("Could not write schwab-transactions.csv.")
return
}
print("Wrote \(csv.numRows.intValue) rows to schwab-transactions.csv.")
}