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

Rust
let mut success = false;

// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false;

let vault = chilkat::Secrets::new();
vault.set_location("local_manager");
vault.set_auto_split(true);
let entry = chilkat::JsonObject::new();
let _ = entry.update_string("appName", "SchwabTrader");
let _ = entry.update_string("service", "OAuth2");
let _ = entry.update_string("username", "personal-desktop");
let tokens = chilkat::JsonObject::new();
success = vault.get_secret_json(&entry, &tokens).is_ok();
if !success {
    println!("Could not read the token record. Check the store and complete desktop authorization first.");
    return;
}

let access_token = tokens.string_of("access_token").unwrap_or_default();
if access_token == "" {
    println!("Run the Schwab authorization or refresh example to save an access token.");
    return;
}

let http = chilkat::Http::new();
http.set_require_ssl_cert_verify(true);
http.set_auth_token(&access_token);

// Read the hash saved by the authorized-account selection example.
let _ = entry.update_string("service", "SelectedAccount");
let selection = chilkat::JsonObject::new();
success = vault.get_secret_json(&entry, &selection).is_ok();
let account_hash = selection.string_of("hashValue").unwrap_or_default();
if (!success) || (account_hash == "") {
    println!("Select an authorized account first.");
    return;
}

let _ = http.set_url_var("account", &account_hash);

// These are illustrative preview inputs. Set the symbol, quantity and limit price.
let order = chilkat::JsonObject::new();
// The PreviewOrder schema puts orderLegs inside orderStrategy.
let _ = order.update_string("orderStrategy.session", "NORMAL");
let _ = order.update_string("orderStrategy.duration", "DAY");
let _ = order.update_string("orderStrategy.orderType", "LIMIT");
let _ = order.update_string("orderStrategy.orderStrategyType", "SINGLE");
let _ = order.update_number("orderStrategy.price", "100.00");
let _ = order.update_int("orderStrategy.quantity", 1);
let _ = order.update_string("orderStrategy.orderLegs[0].instruction", "BUY");
let _ = order.update_int("orderStrategy.orderLegs[0].quantity", 1);
let _ = order.update_string("orderStrategy.orderLegs[0].finalSymbol", "AAPL");
let _ = order.update_string("orderStrategy.orderLegs[0].assetType", "EQUITY");
let resp = chilkat::HttpResponse::new();
success = http.http_json("POST", "https://api.schwabapi.com/trader/v1/accounts/{$account}/previewOrder", &order, "application/json", &resp).is_ok();
if (!success) || (resp.status_code() != 200) {
    if resp.status_code() == 0 {
        println!("No HTTP response. Check connectivity.");
    } else {
        println!("Schwab returned HTTP {}", resp.status_code());
        if resp.status_code() == 401 {
            println!("Refresh the access token or repeat desktop authorization.");
        }

    }

    return;
}

let reply = chilkat::JsonObject::new();
if reply.load(&resp.body_str()).is_err() {
    println!("Schwab returned unexpected JSON.");
    return;
}

println!("Preview only. No order was submitted.");
if reply.has_member("orderStrategy.orderType") {
    println!("Projected order: {}  price {}", reply.string_of("orderStrategy.orderType").unwrap_or_default(), reply.string_of("orderStrategy.price").unwrap_or_default());
}

if reply.has_member("orderStrategy.orderBalance.projectedBuyingPower") {
    println!("Projected buying power: {}", reply.string_of("orderStrategy.orderBalance.projectedBuyingPower").unwrap_or_default());
}

let validation = chilkat::JsonObject::new();
if reply.object_of2("orderValidationResult", &validation).is_err() {
    println!("Schwab supplied no validation result.");
    return;
}

// Each category (accepts, alerts, warns, reviews, rejects) contains rule messages.
let rules = chilkat::JsonArray::new();
let detail = chilkat::JsonObject::new();
let mut messages = 0;
let mut i = 0;
while i < validation.size() {
    let category = validation.name_at(i).unwrap_or_default();
    if validation.array_at2(i, &rules).is_ok() {
        let mut j = 0;
        while j < rules.size() {
            let _ = rules.object_at2(j, &detail);
            println!("{}  {}  {}  {}", category, detail.string_of("validationRuleName").unwrap_or_default(), detail.string_of("message").unwrap_or_default(), detail.string_of("activityMessage").unwrap_or_default());
            messages = messages + 1;
            j = j + 1;
        }

    }

    i = i + 1;
}

if messages == 0 {
    println!("No validation messages returned.");
}