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

Schwab: Inspect an order, its legs, and fills

See more Schwab Examples

Use an order ID from the selected account’s recent orders. The example reads a single order and matches executions to order legs by legId. Each execution can have its own quantity, price, and timestamp. Working orders can have zero or partial fills. The loops cover the returned order’s own legs and activities.

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 Swift Downloads

Swift

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)

    //  Supply the ID as text so large numeric identifiers keep all their digits.
    var orderId: String? = "ORDER_ID_FROM_LIST"
    http.setUrlVar(name: "orderId", value: orderId)
    let resp = CkoHttpResponse()!
    success = http.httpNoBody(verb: "GET", url: "https://api.schwabapi.com/trader/v1/accounts/{$account}/orders/{$orderId}", 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 order = CkoJsonObject()!
    success = order.load(json: resp.bodyStr)
    if success != true {
        print("Schwab returned unexpected JSON.")
        return
    }

    print("Order \(order.string(of: "orderId")!)  \(order.string(of: "status")!)")
    let symbols = CkoJsonObject()!
    var i: Int = 0
    while (i < order.size(ofArray: "orderLegCollection").intValue) {
        order.i = i
        var legId: String? = order.string(of: "orderLegCollection[i].legId")
        var symbol: String? = order.string(of: "orderLegCollection[i].instrument.symbol")
        symbols.updateString(jsonPath: legId, value: symbol)
        print("Leg \(legId!)  \(order.string(of: "orderLegCollection[i].instruction")!) \(order.string(of: "orderLegCollection[i].quantity")!) \(symbol!)")
        i = i + 1
    }

    var fills: Int = 0
    i = 0
    while (i < order.size(ofArray: "orderActivityCollection").intValue) {
        order.i = i
        if order.string(ofEquals: "orderActivityCollection[i].executionType", value: "FILL", caseSensitive: true) == true {
            var j: Int = 0
            while (j < order.size(ofArray: "orderActivityCollection[i].executionLegs").intValue) {
                order.j = j
                var filledLeg: String? = order.string(of: "orderActivityCollection[i].executionLegs[j].legId")
                print("Fill on leg \(filledLeg!)  \(symbols.string(of: filledLeg)!)  quantity \(order.string(of: "orderActivityCollection[i].executionLegs[j].quantity")!)  price \(order.string(of: "orderActivityCollection[i].executionLegs[j].price")!)  time \(order.string(of: "orderActivityCollection[i].executionLegs[j].time")!)")
                fills = fills + 1
                j = j + 1
            }

        }

        i = i + 1
    }

    if fills == 0 {
        print("No fills reported for this order.")
    }


}