Paper and Demo Trading
Use the MyStocks sandbox and integration test tools to validate trading workflows without moving real money.
MyStocks calls its non-production environment Sandbox. It is the equivalent of a paper/demo environment for partner integration testing, but it has its own key prefix and base URL.
| Surface | Key | Base URL | Purpose |
|---|---|---|---|
| Sandbox environment | sk_sandbox_ | /api/sandbox/v1/partner | Isolated virtual accounts and accelerated trading workflows |
| Canonical deterministic test tools | sk_sandbox_ | /api/sandbox/v1/partner/test-tools/* | Simulated order, wallet, holding, execution, and webhook scenarios for new integrations |
| Restricted legacy compatibility | pk_live_ | /api/v1/partner/test-tools/* | Virtual-event testing against approved live webhook configuration; never production trading |
The production-base compatibility surface is not the isolated sandbox. Deprecated /sandbox/* aliases remain only for existing integrations and must not be used in new examples.
What to test
- account creation and auto-registration;
- deposits, withdrawals, and idempotent retries;
- KYC-required and frozen-account behavior;
- quote expiry and mismatched quote rejection;
- market, limit, stop, and cancellation lifecycles;
- insufficient funds and holdings errors;
- webhook signatures, duplicates, ordering, and retry leases;
- SSE reconnect and
Last-Event-IDreplay; - daily reconciliation and statement generation.
Sandbox parity boundaries
The sandbox mirrors the partner-facing treasury and revenue workflows needed for product design:
GET/PATCH/POST /float, GET/PATCH /pricing, and master or sub-account GET /tax-lots and
GET /gains. Pricing and treasury updates are virtual and never alter production settings. Tax lots
and gains are derived from sandbox instant-fill orders using the same FIFO reporting model as production.
The following controls remain production-only and appear as non-executable reference entries in the
API Tester: OAuth client credentials, enterprise security policy, go-live certification, reconciliation
packs, OMS execution reports, SSE streaming, and resting-order replacement. OpenAPI operations declare
this boundary with x-sandbox: false, and CI fails if the route, specification, and tester disagree.
Deterministic execution certification
List a customer's simulated orders with their actual sub-account ID:
Replace usr_abc123 with the ID returned by POST /users. Omitting subAccountId in sandbox
returns 400 MISSING_PARAM; the production compatibility route treats it as an optional filter.
/users
Create sub-account
Full endpoint documentationcreateUsersCreates a new sub-account. Each sub-account has an isolated USD wallet, portfolio, and order book. The externalId is your own reference — it must be unique per partner and is used in all subsequent calls. Sub-accounts start with a walletBalance of $0 — fund them via POST /users/{userId}/deposit.
Parameters
This endpoint has no path or query parameters.
Headers
AuthorizationstringRequiredBearer sk_sandbox_<your_key> for sandbox requests.
Idempotency-KeystringheaderRequiredUnique string that makes write calls safe to retry on network failure. Required for money movement, trading, KYC, subscriptions, and webhook creation. Deduplicated for 24 hours -- duplicate keys return the cached response. HTTP 409 if a concurrent request with the same key is still in progress.
Example: dep_user42_1743152580
Request body
externalIdstringRequiredYour internal user identifier. Must be unique per partner.
Example: "usr_8821"
displayNamestringFull name shown in the MyStocks admin console.
Example: "Alice K."
emailstringEmail address for the sub-account user.
Example: "alice@yourapp.com"
phonestringCustomer phone number in international format when available.
Example: "+254712345678"
countrystringISO 3166-1 alpha-2 country code used for onboarding and compliance context.
Example: "KE"
Response fields
subAccountIdstringMyStocks internal ID. Use in /users/{userId}/... paths.
Example: "usr_abc123"
userIdstringCompatible alias of subAccountId. Use subAccountId as the canonical stored identifier.
externalIdstringYour own user identifier as set at creation.
Example: "usr_8821"
displayNamestring | nullExample: "Alice K."
emailstring | nullExample: "alice@yourapp.com"
kycStatusNONE | PENDING | VERIFIED | REJECTEDVERIFIED required for trading and asset subscriptions. REJECTED remains gated until re-asserted.
kycLevelNONE | BASIC | FULLBASIC = ID verified. FULL = enhanced due diligence.
kycRejectionCodestring | nullStable rejection code when kycStatus is REJECTED.
kycRejectionReasonstring | nullCustomer-safe remediation guidance when kycStatus is REJECTED.
kycReviewedAtstring | nullTimestamp of the rejection decision.
statusactive | frozen | closedwalletBalancenumberCurrent USD wallet balance.
Example: 1250
Response codes
201Sub-account created.409externalId already exists.Expected restrictions and test outcomes
| Request | Expected result and correct test setup |
|---|---|
POST /trade | Master-account trading is unavailable in sandbox and returns 422. Use POST /users/{userId}/trade for a successful virtual trade. |
POST /payout | Sandbox returns 422 because virtual funds cannot be paid out. GET /payout remains available. |
| Enterprise, team, security, approvals, sessions, and support operations | Production-only operations are marked x-sandbox: false and disabled for sandbox keys in the API Tester. An authenticated request to an absent sandbox route returns 404 SANDBOX_UNSUPPORTED. |
| Schema discovery | Fetch OpenAPI JSON or OpenAPI YAML from the site root, without the sandbox API prefix or credentials. |
| Corporate-action election | Read the action first and select a valid option. See election options. |
Exclude production-only operations from sandbox happy-path coverage. Test expected restrictions separately, asserting the response status and error payload. A correct rejection is a passing negative test, not a successful trade or payout. Unknown paths also use the sandbox fallback, so a 404 alone does not establish that the requested operation exists in production.
For replay tests, use a supported mutation, the same idempotency key and identical body (including
clientOrderId), and verify that the wallet/order changes only once. Test changed-body rejection separately.
Advancing a deterministic scenario
Use POST /test-tools/trade on the sandbox base URL to create an isolated lifecycle scenario. Set
outcome to PENDING, FILL, PARTIAL_FILL, REJECT, CANCEL, or FAIL_SETTLEMENT and provide a
deterministic unitPriceUsd. The simulator updates virtual wallet reservations, holdings, execution
records, and the same signed order webhooks used by production.
Advance pending and partially filled scenarios without MyStocks staff:
Repeat with FILL for the remainder, then SETTLE. Use REJECT, CANCEL, or FAIL_SETTLEMENT to
certify terminal failure handling. Every instruction requires an idempotency key so retries cannot
apply the same wallet or holding movement twice.
Sandbox trades may settle instantly and do not reproduce every production timing characteristic. Always run the go-live certification checks before requesting production access.
/test-tools/trade
Submit test trade
Full endpoint documentationcreateTestToolsTradePlaces a deterministic test trade without hitting a real exchange. Recommended: use the sandbox base URL with an sk_sandbox_ key. Set outcome to PENDING, FILL, PARTIAL_FILL, REJECT, CANCEL, or FAIL_SETTLEMENT; sandbox wallet reservations, holdings, execution records, and webhooks are updated consistently. A pending or partially filled order can be advanced with PATCH /test-tools/orders/{orderId}. The production base retains the older live-key integration tool for compatibility: Cheat codes for deterministic outcomes: | Quantity | Outcome | |----------|---------| | 100 | Auto-fills immediately (triggers trade.settled) | | 999 | Auto-rejects immediately (triggers trade.rejected) | | Any other | Enters PENDING state — use admin panel to settle | Formerly POST /sandbox/trade, which remains a supported alias.
Parameters
This endpoint has no path or query parameters.
Headers
AuthorizationstringRequiredBearer sk_sandbox_<your_key> for sandbox requests.
Idempotency-KeystringheaderRequiredUnique string that makes write calls safe to retry on network failure. Required for money movement, trading, KYC, subscriptions, and webhook creation. Deduplicated for 24 hours -- duplicate keys return the cached response. HTTP 409 if a concurrent request with the same key is still in progress.
Example: dep_user42_1743152580
Request body
symbolstringRequiredStock symbol (exchange-qualified or bare ticker).
Example: "SCOM.KE"
typeBUY | SELLRequiredOrder direction.
quantitynumberRequiredNumber of shares. On the sandbox base URL, use outcome for deterministic behavior. The legacy live-key test tool still accepts 100 = instant fill and 999 = instant rejection.
Example: 10
subAccountIdstringSub-account to trade on. BUY checks wallet and escrows; SELL checks held units. Omit to bypass all checks.
notestringFree-text note shown to the admin for labelling test scenarios.
unitPriceUsdnumberDeterministic execution price used by the isolated sandbox simulator.
outcomePENDING | FILL | PARTIAL_FILL | REJECT | CANCEL | FAIL_SETTLEMENTExplicit isolated-sandbox lifecycle outcome. Ignored by the legacy live-key test tool.
partialQuantitynumberRequired when outcome is PARTIAL_FILL; must be less than quantity.
Response fields
orderIdstringUnique order ID. Use to poll status or cancel.
Example: "ord_abc123xyz"
symbolstringExample: "SCOM.KE"
namestringExample: "Safaricom PLC"
exchangestringExample: "NSE"
orderTypeMARKET | LIMIT | STOP | STOP_LIMITOrder type. MARKET orders are quote-gated; LIMIT/STOP/STOP_LIMIT rest as WORKING until triggered.
Example: "LIMIT"
limitPricenumber | nullLimit price in the stock's local currency (LIMIT / STOP_LIMIT only).
stopPricenumber | nullStop price in the stock's local currency (STOP / STOP_LIMIT only).
cancelablebooleanWhether the order can be cancelled now (DELETE). True while PENDING or WORKING.
replaceablebooleanWhether the order can be modified now (PATCH). True only for a WORKING resting order.
typeBUY | SELLstatusPENDING | WORKING | PARTIALLY_FILLED | PROCESSING | COMPLETED | FILLED | REJECTED | CANCELLED | EXPIREDPENDING after submission. WORKING = resting LIMIT/STOP/STOP_LIMIT order waiting for its trigger price (becomes PENDING on trigger). PARTIALLY_FILLED and FILLED are the canonical execution states. REJECTED, CANCELLED, and EXPIRED are terminal outcomes. PROCESSING is a legacy transition alias and COMPLETED is a v1 compatibility alias of FILLED; neither represents custody settlement. Settlement is tracked separately as PENDING, SETTLED, or FAILED.
quoteIdstring | nullPre-trade quote ID consumed by this order.
quoteExpiresAtstring | nullquoteUsdPricenumber | nullclientOrderIdstring | nullPartner-supplied order reference.
omsStatusstring | nullCanonical OMS lifecycle status.
timeInForcestring | nullfilledQuantitynumberremainingQuantitynumberaverageFillPricenumber | nullexecutionVenuestring | nulllastExecutionReportIdstring | nullexecutionSlaunionLive execution SLA clock for orders that have entered the PENDING dealing-desk queue. Null while a resting order is still WORKING.
quantityintegerpriceAtOrdernumberStock price in local currency at submission.
usdPriceAtOrdernumberUSD equivalent of priceAtOrder.
fxRateAtOrdernumber | nullManaged FX rate used for local-to-USD conversion at order submission.
fxSourcestring | nullfxRateAsOfstring | nullfxConversionunionfeenumberTotal fee in USD (base + partner markup).
baseFeenumberMyStocks base broker fee (0.75% of gross).
partnerMarkupFeenumberYour markup fee component. Zero if markupBps = 0.
totalAmountnumberBUY: gross + fee. SELL: gross - fee.
currencystringExample: "USD"
localCurrencystringExample: "KES"
rejectionCodestring | nullStructured rejection code. Populated when status = REJECTED.
rejectionReasonstring | nullFree-text rejection detail provided by the MyStocks internal-book execution service. Populated when status = REJECTED.
cancelledAtstring | nullsettledAtstring | nullSet when custody settlement completes; independent of the canonical FILLED execution state. Legacy completed records that pre-date this field return their immutable completion/creation timestamp as compatibility evidence.
createdAtstringcanonicalStatusPENDING | WORKING | PARTIALLY_FILLED | FILLED | REJECTED | CANCELLED | EXPIREDsettlementStatusPENDING | SETTLED | FAILEDorderLifecyclestring | nullEXPIRED for expiry; expiry is not a rejection.
cancelReasonstring | nullResponse codes
201Test order placed.Existing simulation tools and boundaries
Use POST /test-tools/trade with outcome set to PENDING, FILL, PARTIAL_FILL, REJECT, CANCEL or FAIL_SETTLEMENT. Advance existing orders with PATCH /test-tools/orders/{orderId} using the documented actions. The proposed X-Sandbox-Execution-Outcome headers are not the contract. Corporate-action cash simulations and market-session override endpoints are not currently available.
Actual currency wallets use ?walletContract=2; obtain an FX quote before confirming its quoteId with a stable idempotency key. Trades remain USD-settled. This testing flow does not prove broker settlement, FIX connectivity, hedging or regulatory compliance.
How do I test expiry and a specific rejection?
Create a pending order with the existing test tools, then PATCH its order ID. Send subAccountId with every transition and an Idempotency-Key. Use EXPIRE to close the unfilled remainder, release only unused reservations and preserve earlier fills. The event is order.cancelled, with canonicalStatus: EXPIRED, orderLifecycle: EXPIRED and cancelReason: SIMULATED_EXPIRY. Expiry is not a rejection.
For REJECT, optionally supply rejectionCode: INSUFFICIENT_FUNDS, KYC_REQUIRED, MARKET_CLOSED, COMPLIANCE_HOLD, TECHNICAL_ISSUE or OTHER (the default). The code is saved on the order and included in order.rejected. A code on another action is rejected. Frozen accounts cannot receive any new fills, including a fill followed by simulated settlement failure. They can still cancel, expire, reject or mark existing filled orders settled. These are deterministic virtual tests, not an exchange execution or settlement guarantee.
Corporate-action and market-session simulations require a separate tenant-isolated scenario design; they are not available through these actions or arbitrary request headers.
Was this page useful?
Your signal helps us tighten partner onboarding docs.
Last updated on