Sample code for 30+ languages & platforms
B4X 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 B4X Downloads

B4X
Dim success As Boolean = False

'  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = False

Dim vault As ChilkatSecrets
vault.Initialize("vault")
vault.Location = "local_manager"
vault.AutoSplit = True
Dim entry As ChilkatJsonObject
entry.Initialize
entry.UpdateString("appName", "SchwabTrader")
entry.UpdateString("service", "OAuth2")
entry.UpdateString("username", "personal-desktop")
Dim tokens As ChilkatJsonObject
tokens.Initialize
success = vault.GetSecretJson(entry, tokens)
If success <> True Then
    Log("Could not read the token record. Check the store and complete desktop authorization first.")
    Return
End If

Dim accessToken As String = tokens.StringOf("access_token")
If accessToken = "" Then
    Log("Run the Schwab authorization or refresh example to save an access token.")
    Return
End If

Dim http As ChilkatHttp
http.Initialize("http")
http.RequireSslCertVerify = True
http.AuthToken = accessToken

'  Read the hash saved by the authorized-account selection example.
entry.UpdateString("service", "SelectedAccount")
Dim selection As ChilkatJsonObject
selection.Initialize
success = vault.GetSecretJson(entry, selection)
Dim accountHash As String = selection.StringOf("hashValue")
If (success <> True) Or (accountHash = "") Then
    Log("Select an authorized account first.")
    Return
End If

http.SetUrlVar("account", accountHash)

'  These are illustrative preview inputs. Set the symbol, quantity and limit price.
Dim order As ChilkatJsonObject
order.Initialize
'  The PreviewOrder schema puts orderLegs inside orderStrategy.
order.UpdateString("orderStrategy.session", "NORMAL")
order.UpdateString("orderStrategy.duration", "DAY")
order.UpdateString("orderStrategy.orderType", "LIMIT")
order.UpdateString("orderStrategy.orderStrategyType", "SINGLE")
order.UpdateNumber("orderStrategy.price", "100.00")
order.UpdateInt("orderStrategy.quantity", 1)
order.UpdateString("orderStrategy.orderLegs[0].instruction", "BUY")
order.UpdateInt("orderStrategy.orderLegs[0].quantity", 1)
order.UpdateString("orderStrategy.orderLegs[0].finalSymbol", "AAPL")
order.UpdateString("orderStrategy.orderLegs[0].assetType", "EQUITY")
Dim resp As ChilkatHttpResponse
resp.Initialize
success = http.HttpJson("POST", "https://api.schwabapi.com/trader/v1/accounts/{$account}/previewOrder", order, "application/json", resp)
If (success <> True) Or (resp.StatusCode <> 200) Then
    If resp.StatusCode = 0 Then
        Log("No HTTP response. Check connectivity.")
    Else
        Log("Schwab returned HTTP " & resp.StatusCode)
        If resp.StatusCode = 401 Then
            Log("Refresh the access token or repeat desktop authorization.")
        End If

    End If

    Return
End If

Dim reply As ChilkatJsonObject
reply.Initialize
success = reply.Load(resp.BodyStr)
If success <> True Then
    Log("Schwab returned unexpected JSON.")
    Return
End If


Log("Preview only. No order was submitted.")
If reply.HasMember("orderStrategy.orderType") = True Then
    Log("Projected order: " & reply.StringOf("orderStrategy.orderType") & "  price " & reply.StringOf("orderStrategy.price"))
End If

If reply.HasMember("orderStrategy.orderBalance.projectedBuyingPower") = True Then
    Log("Projected buying power: " & reply.StringOf("orderStrategy.orderBalance.projectedBuyingPower"))
End If

Dim validation As ChilkatJsonObject
validation.Initialize
success = reply.ObjectOf2("orderValidationResult", validation)
If success <> True Then
    Log("Schwab supplied no validation result.")
    Return
End If

'  Each category (accepts, alerts, warns, reviews, rejects) contains rule messages.
Dim rules As ChilkatJsonArray
rules.Initialize
Dim detail As ChilkatJsonObject
detail.Initialize
Dim messages As Int = 0
Dim i As Int = 0
Do While (i < validation.Size)
    Dim category As String = validation.NameAt(i)
    success = validation.ArrayAt2(i, rules)
    If success = True Then
        Dim j As Int = 0
        Do While (j < rules.Size)
            rules.ObjectAt2(j, detail)
            Log(category & "  " & detail.StringOf("validationRuleName") & "  " & detail.StringOf("message") & "  " & detail.StringOf("activityMessage"))
            messages = messages + 1
            j = j + 1
        Loop
    End If

    i = i + 1
Loop
If messages = 0 Then
    Log("No validation messages returned.")
End If