Swift Requires Chilkat v11.0.0+
Swift
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.
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)
// These are illustrative preview inputs. Set the symbol, quantity and limit price.
let order = CkoJsonObject()!
// The PreviewOrder schema puts orderLegs inside orderStrategy.
order.updateString(jsonPath: "orderStrategy.session", value: "NORMAL")
order.updateString(jsonPath: "orderStrategy.duration", value: "DAY")
order.updateString(jsonPath: "orderStrategy.orderType", value: "LIMIT")
order.updateString(jsonPath: "orderStrategy.orderStrategyType", value: "SINGLE")
order.updateNumber(jsonPath: "orderStrategy.price", numericStr: "100.00")
order.updateInt(jsonPath: "orderStrategy.quantity", value: 1)
order.updateString(jsonPath: "orderStrategy.orderLegs[0].instruction", value: "BUY")
order.updateInt(jsonPath: "orderStrategy.orderLegs[0].quantity", value: 1)
order.updateString(jsonPath: "orderStrategy.orderLegs[0].finalSymbol", value: "AAPL")
order.updateString(jsonPath: "orderStrategy.orderLegs[0].assetType", value: "EQUITY")
let resp = CkoHttpResponse()!
success = http.httpJson(verb: "POST", url: "https://api.schwabapi.com/trader/v1/accounts/{$account}/previewOrder", json: order, contentType: "application/json", 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 reply = CkoJsonObject()!
success = reply.load(json: resp.bodyStr)
if success != true {
print("Schwab returned unexpected JSON.")
return
}
print("Preview only. No order was submitted.")
if reply.hasMember(jsonPath: "orderStrategy.orderType") == true {
print("Projected order: \(reply.string(of: "orderStrategy.orderType")!) price \(reply.string(of: "orderStrategy.price")!)")
}
if reply.hasMember(jsonPath: "orderStrategy.orderBalance.projectedBuyingPower") == true {
print("Projected buying power: \(reply.string(of: "orderStrategy.orderBalance.projectedBuyingPower")!)")
}
let validation = CkoJsonObject()!
success = reply.objectOf2(jsonPath: "orderValidationResult", jsonObj: validation)
if success != true {
print("Schwab supplied no validation result.")
return
}
// Each category (accepts, alerts, warns, reviews, rejects) contains rule messages.
let rules = CkoJsonArray()!
let detail = CkoJsonObject()!
var messages: Int = 0
var i: Int = 0
while (i < validation.size.intValue) {
var category: String? = validation.name(at: i)
success = validation.arrayAt2(index: i, jarr: rules)
if success == true {
var j: Int = 0
while (j < rules.size.intValue) {
rules.objectAt2(index: j, jsonObj: detail)
print("\(category!) \(detail.string(of: "validationRuleName")!) \(detail.string(of: "message")!) \(detail.string(of: "activityMessage")!)")
messages = messages + 1
j = j + 1
}
}
i = i + 1
}
if messages == 0 {
print("No validation messages returned.")
}
}