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

PHP
<?php

use Chilkat2\Http;
use Chilkat2\HttpResponse;
use Chilkat2\JsonArray;
use Chilkat2\JsonObject;
use Chilkat2\Secrets;

$success = false;

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

$vault = new Secrets();
$vault->Location = 'local_manager';
$vault->AutoSplit = true;
$entry = new JsonObject();
$entry->UpdateString('appName', 'SchwabTrader');
$entry->UpdateString('service', 'OAuth2');
$entry->UpdateString('username', 'personal-desktop');
$tokens = new JsonObject();
try {
    $vault->GetSecretJson($entry, $tokens);
} catch (\Chilkat2\Exception $e) {
    echo "Could not read the token record. Check the store and complete desktop authorization first.\n";
    exit;
}

$accessToken = $tokens->StringOf('access_token');
if ($accessToken === '') {
    echo "Run the Schwab authorization or refresh example to save an access token.\n";
    exit;
}

$http = new Http();
$http->RequireSslCertVerify = true;
$http->AuthToken = $accessToken;

// Read the hash saved by the authorized-account selection example.
$entry->UpdateString('service', 'SelectedAccount');
$selection = new JsonObject();
try {
    $vault->GetSecretJson($entry, $selection);
    $success = true;
} catch (\Chilkat2\Exception $e) {
    $success = false;
}
$accountHash = $selection->StringOf('hashValue');
if ((!$success) || ($accountHash === '')) {
    echo "Select an authorized account first.\n";
    exit;
}

$http->SetUrlVar('account', $accountHash);

// These are illustrative preview inputs. Set the symbol, quantity and limit price.
$order = new JsonObject();
// 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');
$resp = new HttpResponse();
try {
    $http->HttpJson('POST', 'https://api.schwabapi.com/trader/v1/accounts/{$account}/previewOrder', $order, 'application/json', $resp);
    $success = true;
} catch (\Chilkat2\Exception $e) {
    $success = false;
}
if ((!$success) || ($resp->StatusCode != 200)) {
    if ($resp->StatusCode == 0) {
        echo "No HTTP response. Check connectivity.\n";
    } else {
        echo 'Schwab returned HTTP ', $resp->StatusCode, "\n";
        if ($resp->StatusCode == 401) {
            echo "Refresh the access token or repeat desktop authorization.\n";
        }
    }

    exit;
}

$reply = new JsonObject();
try {
    $reply->Load($resp->BodyStr);
} catch (\Chilkat2\Exception $e) {
    echo "Schwab returned unexpected JSON.\n";
    exit;
}

echo "Preview only. No order was submitted.\n";
if ($reply->HasMember('orderStrategy.orderType')) {
    echo 'Projected order: ', $reply->StringOf('orderStrategy.orderType'), '  price ', $reply->StringOf('orderStrategy.price'), "\n";
}

if ($reply->HasMember('orderStrategy.orderBalance.projectedBuyingPower')) {
    echo 'Projected buying power: ', $reply->StringOf('orderStrategy.orderBalance.projectedBuyingPower'), "\n";
}

$validation = new JsonObject();
try {
    $reply->ObjectOf2('orderValidationResult', $validation);
} catch (\Chilkat2\Exception $e) {
    echo "Schwab supplied no validation result.\n";
    exit;
}

// Each category (accepts, alerts, warns, reviews, rejects) contains rule messages.
$rules = new JsonArray();
$detail = new JsonObject();
$messages = 0;
$i = 0;
while ($i < $validation->Size) {
    $category = $validation->NameAt($i);
    try {
        $validation->ArrayAt2($i, $rules);
        $success = true;
    } catch (\Chilkat2\Exception $e) {
        $success = false;
    }
    if ($success) {
        $j = 0;
        while ($j < $rules->Size) {
            $rules->ObjectAt2($j, $detail);
            echo $category, '  ', $detail->StringOf('validationRuleName'), '  ', $detail->StringOf('message'), '  ', $detail->StringOf('activityMessage'), "\n";
            $messages = $messages + 1;
            $j = $j + 1;
        }
    }

    $i = $i + 1;
}

if ($messages == 0) {
    echo "No validation messages returned.\n";
}