Sample code for 30+ languages & platforms
Lua Requires Chilkat v11.0.0+

Schwab: Preview a single-leg equity limit order

See more Schwab Examples

Builds a day limit order for one share and posts it to previewOrder. Reads the projected order and the validation messages, including warnings and rejection reasons. A successful HTTP response means the preview completed. A preview does not submit an order, reserve buying power, or guarantee later acceptance.

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.

Schwab API specification

Chilkat Lua Downloads

Lua
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)

-- These are illustrative preview inputs. Set the symbol, quantity and limit price.
local order = chilkat.JsonObject.new()
-- The PreviewOrder schema puts orderLegs inside orderStrategy.
order:update_string("orderStrategy.session", "NORMAL")
order:update_string("orderStrategy.duration", "DAY")
order:update_string("orderStrategy.orderType", "LIMIT")
order:update_string("orderStrategy.orderStrategyType", "SINGLE")
order:update_number("orderStrategy.price", "100.00")
order:update_int("orderStrategy.quantity", 1)
order:update_string("orderStrategy.orderLegs[0].instruction", "BUY")
order:update_int("orderStrategy.orderLegs[0].quantity", 1)
order:update_string("orderStrategy.orderLegs[0].finalSymbol", "AAPL")
order:update_string("orderStrategy.orderLegs[0].assetType", "EQUITY")
local resp = chilkat.HttpResponse.new()
success = http:http_json("POST", "https://api.schwabapi.com/trader/v1/accounts/{$account}/previewOrder", order, "application/json", 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

print("Preview only. No order was submitted.")
if reply:has_member("orderStrategy.orderType") then
    print("Projected order: " .. reply:string_of("orderStrategy.orderType") .. "  price " .. reply:string_of("orderStrategy.price"))
end

if reply:has_member("orderStrategy.orderBalance.projectedBuyingPower") then
    print("Projected buying power: " .. reply:string_of("orderStrategy.orderBalance.projectedBuyingPower"))
end

local validation = chilkat.JsonObject.new()
success = reply:object_of2("orderValidationResult", validation)
if not success then
    print("Schwab supplied no validation result.")
    return
end

-- Each category (accepts, alerts, warns, reviews, rejects) contains rule messages.
local rules = chilkat.JsonArray.new()
local detail = chilkat.JsonObject.new()
local messages = 0
local i = 0
while i < validation.size do
    local category = validation:name_at(i)
    success = validation:array_at2(i, rules)
    if success then
        local j = 0
        while j < rules.size do
            rules:object_at2(j, detail)
            print(category .. "  " .. detail:string_of("validationRuleName") .. "  " .. detail:string_of("message") .. "  " .. detail:string_of("activityMessage"))
            messages = messages + 1
            j = j + 1
        end
    end

    i = i + 1
end

if messages == 0 then
    print("No validation messages returned.")
end