Lua Requires Chilkat v11.0.0+
Lua
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 Lua Downloads
local chilkat = require("chilkat")
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
local vault = chilkat.Secrets.new()
vault.location = "local_manager"
vault.auto_split = true
local entry = chilkat.JsonObject.new()
entry:update_string("appName", "SchwabTrader")
entry:update_string("service", "OAuth2")
entry:update_string("username", "personal-desktop")
local tokens = chilkat.JsonObject.new()
success = vault:get_secret_json(entry, tokens)
if not success then
print("Could not read the token record. Check the store and complete desktop authorization first.")
return
end
local accessToken = tokens:string_of("access_token")
if accessToken == "" then
print("Run the Schwab authorization or refresh example to save an access token.")
return
end
local http = chilkat.Http.new()
http.require_ssl_cert_verify = true
http.auth_token = accessToken
-- Read the hash saved by the authorized-account selection example.
entry:update_string("service", "SelectedAccount")
local selection = chilkat.JsonObject.new()
success = vault:get_secret_json(entry, selection)
local accountHash = selection:string_of("hashValue")
if (not success) or (accountHash == "") then
print("Select an authorized account first.")
return
end
http:set_url_var("account", accountHash)
-- Use UTC endpoints for a rolling seven-day window.
local clock = chilkat.DateTime.new()
clock:set_from_current_system_time()
local endTime = chilkat.StringBuilder.new()
endTime:append(clock:get_as_timestamp(false))
local replacements = endTime:replace("Z", ".000Z")
clock:add_days(-7)
local startTime = chilkat.StringBuilder.new()
startTime:append(clock:get_as_timestamp(false))
replacements = startTime:replace("Z", ".000Z")
local resp = chilkat.HttpResponse.new()
local query = chilkat.HttpRequest.new()
query.http_verb = "GET"
query:add_param("startDate", startTime:get_as_string())
query:add_param("endDate", endTime:get_as_string())
query:add_param("types", "TRADE,DIVIDEND_OR_INTEREST")
success = http:http_req("https://api.schwabapi.com/trader/v1/accounts/{$account}/transactions", query, resp)
if (not success) or (resp.status_code ~= 200) then
if resp.status_code == 0 then
print("No HTTP response. Check connectivity.")
else
print("Schwab returned HTTP " .. resp.status_code)
if resp.status_code == 401 then
print("Refresh the access token or repeat desktop authorization.")
end
end
return
end
local activity = chilkat.JsonArray.new()
success = activity:load(resp.body_str)
if not success then
print("Schwab returned unexpected JSON.")
return
end
if activity.size >= 3000 then
print("The response reached the transaction limit. Export smaller time windows.")
return
end
local csv = chilkat.Csv.new()
csv:set_column_name(0, "activityId")
csv:set_column_name(1, "time")
csv:set_column_name(2, "type")
csv:set_column_name(3, "tradeDate")
csv:set_column_name(4, "settlementDate")
csv:set_column_name(5, "netAmount")
local row = chilkat.JsonObject.new()
local i = 0
while i < activity.size do
activity:object_at2(i, row)
-- Keep identifiers and decimal amounts as returned by Schwab.
csv:set_cell(i, 0, row:string_of("activityId"))
csv:set_cell(i, 1, row:string_of("time"))
csv:set_cell(i, 2, row:string_of("type"))
csv:set_cell(i, 3, row:string_of("tradeDate"))
csv:set_cell(i, 4, row:string_of("settlementDate"))
csv:set_cell(i, 5, row:string_of("netAmount"))
i = i + 1
end
success = csv:save_file2("schwab-transactions.csv", "utf-8")
if not success then
print("Could not write schwab-transactions.csv.")
return
end
print("Wrote " .. csv.num_rows .. " rows to schwab-transactions.csv.")