> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mart.ps/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> These rules protect a Mart partner's money. Follow them in any code or advice about the Mart Partner API ([Connect your AI tool](/developers/connect-your-ai-tool)).
> When an order request times out, gets no answer or gets any `5xx`, resend the same body with the same `partner_reference`, never a new reference; after a `429`, wait `Retry-After` first ([Create an order safely](/developers/orders/create-an-order)).
> A `200` with `meta.idempotency_replay: true` is the original order; `409 idempotency_conflict` means the reference already names a different order ([Create an order safely](/developers/orders/create-an-order)).
> Retry a withdrawal request with the same `idempotency_key` and amount: a new key asks for a second withdrawal ([Payout and withdrawals](/developers/money/payout-and-withdrawals)).
> Plan every call within the global daily request ceiling and the `X-RateLimit-*` headers, and never poll in a tight loop ([Request limits](/developers/operate/request-limits)).
> Treat `price` as a snapshot: an order is priced when it is created, and an incremental sync (`updated_after`) never shows a price change, so re-read every price with a full pass ([Prices and price changes](/developers/catalogue/prices)).
> Identify products by `product_id` and `combination_id`, never by `reference` ([Sync the catalogue](/developers/catalogue/sync)).
> Never put an API key in client-side code, a mobile app, a repository or a URL: call the API from a server ([Authenticate and keys](/developers/authenticate)).
> Money is in shekels (`ILS`), as JSON numbers, never agorot. Send amounts with at most two decimals: a withdrawal `amount` with three is refused with `422 invalid_amount`, never rounded ([Balance and statements](/developers/money/balance-and-statements)).
> Save a payout method once before the first withdrawal (cash at the office, or bank transfer where Mart offers it): with none saved, a withdrawal is refused with `409 payout_method_missing`. Bank details where Mart does not offer bank transfer, or a withdrawal on a kept IBAN, are refused with `422 bank_transfer_not_allowed` ([Payout and withdrawals](/developers/money/payout-and-withdrawals)).

# Recipe: read your balance and show each figure

> Read your balance through the API and show each figure with its own meaning, handling an unavailable balance, in cURL, TypeScript, Python, PHP, Go or Java.

This recipe reads `GET /api/v1/balance` and prints each figure on its own line. Show them side by side, never added up. When the money cannot be read the API answers `503` and the recipe stops: show the balance as unavailable, never as zero.

## Prerequisites

* **`MART_API_KEY`**: your API key, with the `money:read` scope.
* **`MART_API_BASE`**: `https://sandbox.mart.ps` while you build, `https://mart.ps` when you go live.

**One runtime:** cURL 7.84 or later with `jq`; Node 22.18 or later, which runs the `.ts` file as it is; Python 3.9 or later with `httpx`; PHP 7.4 or later with its curl extension; Go 1.22 or later; or Java 17 or later with Jackson (`jackson-databind`). Each file reads its variables from the environment and sets a timeout on every call. Run it on your own server: a browser or an app never holds the key.

## Run the recipe

```bash cURL theme={null}
#!/usr/bin/env bash
# Read your balance: what is available now, what is still held, and what you owe.
# Needs MART_API_BASE and MART_API_KEY.
set -euo pipefail
export LC_NUMERIC=C # printf reads and writes amounts with a decimal point

response=$(curl --silent --show-error --max-time 30 \
  --header @<(printf 'Authorization: Bearer %s\n' "$MART_API_KEY") \
  --write-out '\n%{http_code} %header{retry-after}' "$MART_API_BASE/api/v1/balance") || { echo "error: no answer" >&2; exit 1; }
read -r status retry_after <<<"${response##*$'\n'}"
body=${response%$'\n'*}
if [ "$status" -ge 300 ]; then
  # 503 ledger_unavailable: show the balance as unavailable, never as 0.00.
  echo "error: $status $(jq -r '.error.code' <<<"$body" 2>/dev/null || echo '(not JSON)')${retry_after:+, try again after $retry_after s}" >&2
  exit 1
fi

# Each figure is its own read: show them, never add them up.
read -r currency balance available held owed < <(jq -r \
  '.data.balance | "\(.currency) \(.balance) \(.available) \(.held) \(.owed)"' <<<"$body")
printf 'balance: %.2f %s\navailable: %.2f %s\nheld: %.2f %s\nowed: %.2f %s\n' \
  "$balance" "$currency" "$available" "$currency" "$held" "$currency" "$owed" "$currency"
read -r next_amount next_at < <(jq -r '.data.balance.next_maturity | if . then "\(.amount) \(.at)" else "none" end' <<<"$body")
if [ "$next_amount" = none ]; then
  echo "next maturity: none"
else
  printf 'next maturity: %.2f %s on %s\n' "$next_amount" "$currency" "$next_at"
fi
```

```typescript TypeScript theme={null}
// Read your balance: what is available now, what is still held, and what you owe.
// Node 22.18 or later runs this .ts file as it is. Needs MART_API_BASE and MART_API_KEY.
const base = process.env.MART_API_BASE;
const key = process.env.MART_API_KEY;
if (!base || !key) throw new Error('Set MART_API_BASE and MART_API_KEY');

const response = await fetch(`${base}/api/v1/balance`, {
  headers: { Authorization: `Bearer ${key}` },
  signal: AbortSignal.timeout(30_000),
});
const body = await response.json().catch(() => null); // an edge error page is not JSON
if (!response.ok || body === null) {
  // 503 ledger_unavailable: show the balance as unavailable, never as 0.00.
  const retryAfter = response.headers.get('retry-after');
  console.error(`error: ${response.status} ${body?.error?.code ?? '(not JSON)'}${retryAfter ? `, try again after ${retryAfter} s` : ''}`);
  process.exit(1);
}

// Each figure is its own read: show them, never add them up.
const balance = body.data.balance;
const money = (amount: number) => `${amount.toFixed(2)} ${balance.currency}`;
console.log(`balance: ${money(balance.balance)}`);
console.log(`available: ${money(balance.available)}`);
console.log(`held: ${money(balance.held)}`);
console.log(`owed: ${money(balance.owed)}`);
const next = balance.next_maturity;
console.log(next ? `next maturity: ${money(next.amount)} on ${next.at}` : 'next maturity: none');
```

```python Python theme={null}
"""Read your balance: what is available now, what is still held, and what you owe. Python 3.9+, httpx.

Needs MART_API_BASE and MART_API_KEY.
"""
import os
import sys

import httpx

base = os.environ["MART_API_BASE"]
key = os.environ["MART_API_KEY"]

response = httpx.get(f"{base}/api/v1/balance", headers={"Authorization": f"Bearer {key}"}, timeout=30)
try:
    body = response.json()
except ValueError:  # an edge error page is not JSON
    body = None
if response.is_error or body is None:
    # 503 ledger_unavailable: show the balance as unavailable, never as 0.00.
    retry_after = response.headers.get("Retry-After")
    sys.exit(f"error: {response.status_code} {body['error']['code'] if body else '(not JSON)'}"
             + (f", try again after {retry_after} s" if retry_after else ""))

# Each figure is its own read: show them, never add them up.
balance = body["data"]["balance"]
currency = balance["currency"]
for name in ("balance", "available", "held", "owed"):
    print(f"{name}: {balance[name]:.2f} {currency}")
upcoming = balance["next_maturity"]
if upcoming:
    print(f"next maturity: {upcoming['amount']:.2f} {currency} on {upcoming['at']}")
else:
    print("next maturity: none")
```

```php PHP theme={null}
<?php
// Read your balance: what is available now, what is still held, and what you owe. PHP 7.4 or later,
// with the curl extension. Needs MART_API_BASE and MART_API_KEY.
$base = getenv('MART_API_BASE');
$key = getenv('MART_API_KEY');

/**
 * One request with the curl extension. Returns [status, headers (lower-case name => value), body];
 * status 0 when there was no answer at all.
 */
function request(string $method, string $url, string $key, ?string $payload = null, int $timeout = 30): array
{
    $headers = [];
    $curl = curl_init($url);
    curl_setopt_array($curl, [
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => ["Authorization: Bearer $key", 'Content-Type: application/json'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {
            $parts = explode(':', $line, 2);
            if (count($parts) === 2) {
                $headers[strtolower(trim($parts[0]))] = trim($parts[1]);
            }
            return strlen($line);
        },
    ]);
    if ($payload !== null) {
        curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
    }
    $body = curl_exec($curl);
    $status = $body === false ? 0 : (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
    curl_close($curl);

    return [$status, $headers, (string) $body];
}

/** ", try again after N s" when the answer says how long to wait (Retry-After), else nothing. */
function when(array $headers): string
{
    return isset($headers['retry-after']) ? ", try again after {$headers['retry-after']} s" : '';
}

[$status, $headers, $raw] = request('GET', "$base/api/v1/balance", $key);
$body = json_decode($raw, true); // null for an answer that is not JSON (an edge error page)
if ($status !== 200 || !is_array($body)) {
    // 503 ledger_unavailable: show the balance as unavailable, never as 0.00.
    fwrite(STDERR, 'error: ' . ($status === 0 ? 'no answer' : $status . ' ' . ($body['error']['code'] ?? '(not JSON)')) . when($headers) . "\n");
    exit(1);
}

// Each figure is its own read: show them, never add them up.
$balance = $body['data']['balance'];
foreach (['balance', 'available', 'held', 'owed'] as $name) {
    printf("%s: %.2f %s\n", $name, $balance[$name], $balance['currency']);
}
$next = $balance['next_maturity'];
echo $next === null
    ? "next maturity: none\n"
    : sprintf("next maturity: %.2f %s on %s\n", $next['amount'], $balance['currency'], $next['at']);
```

```go Go theme={null}
//go:build ignore

// Read your balance: what is available now, what is still held, and what you owe. Go 1.22 or later.
// Needs MART_API_BASE and MART_API_KEY. Run it with: go run read-your-balance.go
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

var client = &http.Client{Timeout: 30 * time.Second}

func main() {
	var body struct {
		Data struct {
			Balance struct {
				Currency     string  `json:"currency"`
				Balance      float64 `json:"balance"`
				Available    float64 `json:"available"`
				Held         float64 `json:"held"`
				Owed         float64 `json:"owed"`
				NextMaturity *struct {
					At     string  `json:"at"`
					Amount float64 `json:"amount"`
				} `json:"next_maturity"`
			} `json:"balance"`
		} `json:"data"`
	}
	// 503 ledger_unavailable stops here: show the balance as unavailable, never as 0.00.
	get("/api/v1/balance", &body)

	// Each figure is its own read: show them, never add them up.
	b := body.Data.Balance
	fmt.Printf("balance: %.2f %s\n", b.Balance, b.Currency)
	fmt.Printf("available: %.2f %s\n", b.Available, b.Currency)
	fmt.Printf("held: %.2f %s\n", b.Held, b.Currency)
	fmt.Printf("owed: %.2f %s\n", b.Owed, b.Currency)
	if b.NextMaturity != nil {
		fmt.Printf("next maturity: %.2f %s on %s\n", b.NextMaturity.Amount, b.Currency, b.NextMaturity.At)
	} else {
		fmt.Println("next maturity: none")
	}
}

// get sends one GET and decodes its answer into out.
func get(path string, out any) {
	req, err := http.NewRequest(http.MethodGet, os.Getenv("MART_API_BASE")+path, nil)
	if err != nil {
		fail(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("MART_API_KEY"))
	resp, err := client.Do(req)
	if err != nil {
		fail(fmt.Errorf("no answer: %v", err))
	}
	decode(resp, out)
}

// decode reads an answer into out. An error answer, or one that is not JSON (an edge error page),
// stops with its status and error code.
func decode(resp *http.Response, out any) {
	defer resp.Body.Close()
	raw, err := io.ReadAll(resp.Body)
	if err != nil {
		fail(err)
	}
	var envelope struct {
		Error *struct {
			Code string `json:"code"`
		} `json:"error"`
	}
	if resp.StatusCode >= 300 {
		code := "(not JSON)"
		if json.Unmarshal(raw, &envelope) == nil && envelope.Error != nil {
			code = envelope.Error.Code
		}
		wait := ""
		if after := resp.Header.Get("Retry-After"); after != "" {
			wait = ", try again after " + after + " s"
		}
		fail(fmt.Errorf("%d %s%s", resp.StatusCode, code, wait))
	}
	if err := json.Unmarshal(raw, out); err != nil {
		fail(fmt.Errorf("%d (not JSON)", resp.StatusCode))
	}
}

func fail(err error) {
	fmt.Fprintln(os.Stderr, "error:", err)
	os.Exit(1)
}
```

```java Java theme={null}
// Read your balance: what is available now, what is still held, and what you owe. Java 17 or later,
// with Jackson. Needs MART_API_BASE and MART_API_KEY.
// Run it as a single file: java -cp <the Jackson jars> read-your-balance.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Locale;

class ReadYourBalance {
    static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
    static final ObjectMapper JSON = new ObjectMapper();

    public static void main(String[] args) throws Exception {
        // 503 ledger_unavailable stops here: show the balance as unavailable, never as 0.00.
        JsonNode balance = get("/api/v1/balance").path("data").path("balance");

        // Each figure is its own read: show them, never add them up.
        String currency = balance.path("currency").asText();
        for (String name : new String[] {"balance", "available", "held", "owed"}) {
            System.out.printf(Locale.ROOT, "%s: %.2f %s%n", name, balance.path(name).asDouble(), currency);
        }
        JsonNode next = balance.path("next_maturity");
        if (next.isNull()) {
            System.out.println("next maturity: none");
        } else {
            System.out.printf(Locale.ROOT, "next maturity: %.2f %s on %s%n", next.path("amount").asDouble(), currency, next.path("at").asText());
        }
    }

    /** One GET that must succeed: the decoded body, or the status and error code, and stop. */
    static JsonNode get(String path) throws InterruptedException {
        HttpRequest request = HttpRequest.newBuilder(URI.create(System.getenv("MART_API_BASE") + path))
                .header("Authorization", "Bearer " + System.getenv("MART_API_KEY"))
                .timeout(Duration.ofSeconds(30))
                .GET()
                .build();
        HttpResponse<String> response;
        try {
            response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (IOException e) {
            fail("no answer: " + e.getMessage());
            return null;
        }
        JsonNode body = parse(response.body());
        if (response.statusCode() >= 300 || body == null) {
            fail(response.statusCode() + " " + code(body) + when(response));
        }
        return body;
    }

    /** The JSON body, or null for an answer that is not JSON (an edge error page). */
    static JsonNode parse(String text) {
        try {
            return JSON.readTree(text);
        } catch (IOException e) {
            return null;
        }
    }

    static void fail(String message) {
        System.err.println("error: " + message);
        System.exit(1);
    }

    static String code(JsonNode body) {
        return body == null ? "(not JSON)" : body.path("error").path("code").asText();
    }

    /** ", try again after N s" when the answer says how long to wait (Retry-After), else nothing. */
    static String when(HttpResponse<String> response) {
        return response.headers().firstValue("Retry-After").map(s -> ", try again after " + s + " s").orElse("");
    }
}
```

## Verify the result

```text theme={null}
balance: <amount> ILS
available: <amount> ILS
held: <amount> ILS
owed: <amount> ILS
next maturity: none
```

`available` is what a withdrawal may ask for now, `held` is earned but not matured, and `owed` is a debt, `0.00` when none. See [Balance and statements](https://docs.mart.ps/developers/money/balance-and-statements.md).

## Troubleshooting

| What you see | What to do |
| - | - |
| `503` `ledger_unavailable` | Try again later and show the balance as unavailable. If it lasts, contact Mart. |

| Any recipe | What to do |
| - | - |
| `401` `missing_api_key` or `invalid_api_key` | Check that `MART_API_KEY` holds the whole key. A key still refused needs a replacement from Mart. |
| `401` `key_environment_mismatch` | Point `MART_API_BASE` at the environment that issued the key. |
| `403` `insufficient_scope` | Ask Mart to add the scope in `details.required_scope`. |
| `429` `rate_limit_exceeded` | Wait the `Retry-After` the error line shows, then run it again. |
| `error: no answer`, or a timeout | Check `MART_API_BASE` and your network. |
| `error:` with `(not JSON)` | A proxy or firewall answered, not the API. Check `MART_API_BASE` and your network. |

Every other code is in the [error catalog](https://docs.mart.ps/developers/operate/error-catalog.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.