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

Objective-C
#import <CkoSecrets.h>
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoHttp.h>
#import <CkoHttpResponse.h>
#import <CkoJsonArray.h>

BOOL success = NO;

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

CkoSecrets *vault = [[CkoSecrets alloc] init];
vault.Location = @"local_manager";
vault.AutoSplit = YES;
CkoJsonObject *entry = [[CkoJsonObject alloc] init];
[entry UpdateString: @"appName" value: @"SchwabTrader"];
[entry UpdateString: @"service" value: @"OAuth2"];
[entry UpdateString: @"username" value: @"personal-desktop"];
CkoJsonObject *tokens = [[CkoJsonObject alloc] init];
success = [vault GetSecretJson: entry jsonOut: tokens];
if (success != YES) {
    NSLog(@"%@",@"Could not read the token record. Check the store and complete desktop authorization first.");
    return;
}

NSString *accessToken = [tokens StringOf: @"access_token"];
if (accessToken == @"") {
    NSLog(@"%@",@"Run the Schwab authorization or refresh example to save an access token.");
    return;
}

CkoHttp *http = [[CkoHttp alloc] init];
http.RequireSslCertVerify = YES;
http.AuthToken = accessToken;

//  Read the hash saved by the authorized-account selection example.
[entry UpdateString: @"service" value: @"SelectedAccount"];
CkoJsonObject *selection = [[CkoJsonObject alloc] init];
success = [vault GetSecretJson: entry jsonOut: selection];
NSString *accountHash = [selection StringOf: @"hashValue"];
if ((success != YES) || (accountHash == @"")) {
    NSLog(@"%@",@"Select an authorized account first.");
    return;
}

[http SetUrlVar: @"account" value: accountHash];

//  These are illustrative preview inputs. Set the symbol, quantity and limit price.
CkoJsonObject *order = [[CkoJsonObject alloc] init];
//  The PreviewOrder schema puts orderLegs inside orderStrategy.
[order UpdateString: @"orderStrategy.session" value: @"NORMAL"];
[order UpdateString: @"orderStrategy.duration" value: @"DAY"];
[order UpdateString: @"orderStrategy.orderType" value: @"LIMIT"];
[order UpdateString: @"orderStrategy.orderStrategyType" value: @"SINGLE"];
[order UpdateNumber: @"orderStrategy.price" numericStr: @"100.00"];
[order UpdateInt: @"orderStrategy.quantity" value: [NSNumber numberWithInt: 1]];
[order UpdateString: @"orderStrategy.orderLegs[0].instruction" value: @"BUY"];
[order UpdateInt: @"orderStrategy.orderLegs[0].quantity" value: [NSNumber numberWithInt: 1]];
[order UpdateString: @"orderStrategy.orderLegs[0].finalSymbol" value: @"AAPL"];
[order UpdateString: @"orderStrategy.orderLegs[0].assetType" value: @"EQUITY"];
CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];
success = [http HttpJson: @"POST" url: @"https://api.schwabapi.com/trader/v1/accounts/{$account}/previewOrder" json: order contentType: @"application/json" response: resp];
if ((success != YES) || ([resp.StatusCode intValue] != 200)) {
    if ([resp.StatusCode intValue] == 0) {
        NSLog(@"%@",@"No HTTP response. Check connectivity.");
    }
    else {
        NSLog(@"%@%d",@"Schwab returned HTTP ",[resp.StatusCode intValue]);
        if ([resp.StatusCode intValue] == 401) {
            NSLog(@"%@",@"Refresh the access token or repeat desktop authorization.");
        }

    }

    return;
}

CkoJsonObject *reply = [[CkoJsonObject alloc] init];
success = [reply Load: resp.BodyStr];
if (success != YES) {
    NSLog(@"%@",@"Schwab returned unexpected JSON.");
    return;
}

NSLog(@"%@",@"Preview only. No order was submitted.");
if ([reply HasMember: @"orderStrategy.orderType"] == YES) {
    NSLog(@"%@%@%@%@",@"Projected order: ",[reply StringOf: @"orderStrategy.orderType"],@"  price ",[reply StringOf: @"orderStrategy.price"]);
}

if ([reply HasMember: @"orderStrategy.orderBalance.projectedBuyingPower"] == YES) {
    NSLog(@"%@%@",@"Projected buying power: ",[reply StringOf: @"orderStrategy.orderBalance.projectedBuyingPower"]);
}

CkoJsonObject *validation = [[CkoJsonObject alloc] init];
success = [reply ObjectOf2: @"orderValidationResult" jsonObj: validation];
if (success != YES) {
    NSLog(@"%@",@"Schwab supplied no validation result.");
    return;
}

//  Each category (accepts, alerts, warns, reviews, rejects) contains rule messages.
CkoJsonArray *rules = [[CkoJsonArray alloc] init];
CkoJsonObject *detail = [[CkoJsonObject alloc] init];
int messages = 0;
int i = 0;
while ((i < [validation.Size intValue])) {
    NSString *category = [validation NameAt: [NSNumber numberWithInt: i]];
    success = [validation ArrayAt2: [NSNumber numberWithInt: i] jarr: rules];
    if (success == YES) {
        int j = 0;
        while ((j < [rules.Size intValue])) {
            [rules ObjectAt2: [NSNumber numberWithInt: j] jsonObj: detail];
            NSLog(@"%@%@%@%@%@%@%@",category,@"  ",[detail StringOf: @"validationRuleName"],@"  ",[detail StringOf: @"message"],@"  ",[detail StringOf: @"activityMessage"]);
            messages = messages + 1;
            j = j + 1;
        }

    }

    i = i + 1;
}

if (messages == 0) {
    NSLog(@"%@",@"No validation messages returned.");
}