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

Schwab: Read account balances and positions

See more Schwab Examples

Requests fields=positions for the selected account. Reads current cash and liquidation value, prints buying power when supplied, and reports each holding’s symbol, long and short quantities, and market value. A cash-only portfolio can have balances and zero positions.

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)

    let resp = CkoHttpResponse()!
    let query = CkoHttpRequest()!
    query.httpVerb = "GET"
    query.addParam(name: "fields", value: "positions")
    success = http.httpReq(url: "https://api.schwabapi.com/trader/v1/accounts/{$account}", request: query, 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
    }

    let balances = CkoJsonObject()!
    success = reply.objectOf2(jsonPath: "securitiesAccount.currentBalances", jsonObj: balances)
    if success != true {
        print("The account response contained no current balances.")
        return
    }

    print("Cash balance: \(balances.string(of: "cashBalance")!)")
    print("Liquidation value: \(balances.string(of: "liquidationValue")!)")
    if balances.hasMember(jsonPath: "buyingPower") == true {
        print("Buying power: \(balances.string(of: "buyingPower")!)")
    }

    var count: Int = reply.size(ofArray: "securitiesAccount.positions").intValue
    if count <= 0 {
        print("No positions.")
    }

    var i: Int = 0
    while (i < count) {
        reply.i = i
        print("\(reply.string(of: "securitiesAccount.positions[i].instrument.symbol")!)  long \(reply.string(of: "securitiesAccount.positions[i].longQuantity")!)  short \(reply.string(of: "securitiesAccount.positions[i].shortQuantity")!)  market value \(reply.string(of: "securitiesAccount.positions[i].marketValue")!)")
        i = i + 1
    }


}