Lua Requires Chilkat v11.0.0+
Lua
Schwab: Get quotes for a watchlist
See more Schwab Examples
Requests several symbols in one call and prints the bid, ask, last price, quote timestamp in Unix milliseconds, and the real-time indicator when available. Missing quote fields can occur for individual instruments. The response uses symbol names as JSON keys and can report invalid symbols alongside valid quotes.
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.
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
local resp = chilkat.HttpResponse.new()
local query = chilkat.HttpRequest.new()
query.http_verb = "GET"
query:add_param("symbols", "AAPL,MSFT,BRK/B")
query:add_param("fields", "quote")
success = http:http_req("https://api.schwabapi.com/marketdata/v1/quotes", 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 reply = chilkat.JsonObject.new()
success = reply:load(resp.body_str)
if not success then
print("Schwab returned unexpected JSON.")
return
end
-- Read members by index. A symbol may contain punctuation meaningful in a JSON path.
local instrument = chilkat.JsonObject.new()
local i = 0
while i < reply.size do
local key = reply:name_at(i)
if key ~= "errors" then
success = reply:object_at2(i, instrument)
if success then
print(key .. " bid " .. instrument:string_of("quote.bidPrice") .. " ask " .. instrument:string_of("quote.askPrice") .. " last " .. instrument:string_of("quote.lastPrice"))
print(" quote time (Unix ms): " .. instrument:string_of("quote.quoteTime") .. " real-time: " .. instrument:string_of("realtime"))
end
end
i = i + 1
end
local j = 0
while j < reply:size_of_array("errors.invalidSymbols") do
reply.j = j
print("Invalid symbol: " .. reply:string_of("errors.invalidSymbols[j]"))
j = j + 1
end