> For the complete documentation index, see [llms.txt](https://docs.infoway.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.infoway.io/en-docs/rest-api/code-example.md).

# Code Example

All examples below use the stock endpoints. To query another market, replace `stock` in the path with `japan` / `india` / `korea` / `taiwan` / `crypto` / `common`.

Every endpoint authenticates through the `apiKey` request header.

## Latest Trade

`GET /stock/batch_trade/{codes}`

{% tabs %}
{% tab title="Go" %}

```go
package main

import (
	"fmt"
	"io"
	"net/http"
	"time"
)

func main() {
	// Comma-separated, up to 100 symbols
	apiURL := "https://data.infoway.io/stock/batch_trade/TSLA.US,AAPL.US"

	req, err := http.NewRequest("GET", apiURL, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}
	req.Header.Set("Accept", "application/json")
	req.Header.Set("apiKey", "yourApikey")

	client := &http.Client{Timeout: 10 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}

	fmt.Printf("HTTP code: %d\n", resp.StatusCode)
	fmt.Printf("message: %s\n", body)
}
```

{% endtab %}

{% tab title="Java" %}

```java
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;

public class TradeExample {
    public static void main(String[] args) throws IOException, InterruptedException {
        // Comma-separated, up to 100 symbols
        String apiUrl = "https://data.infoway.io/stock/batch_trade/TSLA.US,AAPL.US";

        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();

        HttpRequest request = HttpRequest.newBuilder(URI.create(apiUrl))
                .timeout(Duration.ofSeconds(10))
                .header("Accept", "application/json")
                .header("apiKey", "yourApikey")
                .GET()
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("HTTP code: " + response.statusCode());
        System.out.println("message: " + response.body());
    }
}
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
// Node.js 18+ or the browser fetch API (top-level await; save as .mjs on Node)
// Comma-separated, up to 100 symbols
const apiUrl = 'https://data.infoway.io/stock/batch_trade/TSLA.US,AAPL.US';

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 10000);

try {
  const response = await fetch(apiUrl, {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      apiKey: 'yourApikey',
    },
    signal: controller.signal,
  });

  console.log(`HTTP code: ${response.status}`);
  console.log(`message: ${await response.text()}`);
} catch (err) {
  console.error('Error sending request:', err);
} finally {
  clearTimeout(timer);
}
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
// Comma-separated, up to 100 symbols
$apiUrl = 'https://data.infoway.io/stock/batch_trade/TSLA.US,AAPL.US';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Accept: application/json',
    'apiKey: yourApikey',
]);

$response = curl_exec($ch);
if ($response === false) {
    echo 'Error sending request: ' . curl_error($ch) . PHP_EOL;
    curl_close($ch);
    exit(1);
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo "HTTP code: $httpCode" . PHP_EOL;
echo "message: $response" . PHP_EOL;
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

# Comma-separated, up to 100 symbols
api_url = 'https://data.infoway.io/stock/batch_trade/TSLA.US,AAPL.US'

headers = {
    'Accept': 'application/json',
    'apiKey': 'yourApikey',
}

response = requests.get(api_url, headers=headers, timeout=10)

print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")
```

{% endtab %}
{% endtabs %}

## Market Depth

`GET /stock/batch_depth/{codes}`

{% tabs %}
{% tab title="Go" %}

```go
package main

import (
	"fmt"
	"io"
	"net/http"
	"time"
)

func main() {
	// Comma-separated, up to 100 symbols
	apiURL := "https://data.infoway.io/stock/batch_depth/TSLA.US,AAPL.US"

	req, err := http.NewRequest("GET", apiURL, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}
	req.Header.Set("Accept", "application/json")
	req.Header.Set("apiKey", "yourApikey")

	client := &http.Client{Timeout: 10 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}

	fmt.Printf("HTTP code: %d\n", resp.StatusCode)
	fmt.Printf("message: %s\n", body)
}
```

{% endtab %}

{% tab title="Java" %}

```java
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;

public class DepthExample {
    public static void main(String[] args) throws IOException, InterruptedException {
        // Comma-separated, up to 100 symbols
        String apiUrl = "https://data.infoway.io/stock/batch_depth/TSLA.US,AAPL.US";

        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();

        HttpRequest request = HttpRequest.newBuilder(URI.create(apiUrl))
                .timeout(Duration.ofSeconds(10))
                .header("Accept", "application/json")
                .header("apiKey", "yourApikey")
                .GET()
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("HTTP code: " + response.statusCode());
        System.out.println("message: " + response.body());
    }
}
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
// Node.js 18+ or the browser fetch API (top-level await; save as .mjs on Node)
// Comma-separated, up to 100 symbols
const apiUrl = 'https://data.infoway.io/stock/batch_depth/TSLA.US,AAPL.US';

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 10000);

try {
  const response = await fetch(apiUrl, {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      apiKey: 'yourApikey',
    },
    signal: controller.signal,
  });

  console.log(`HTTP code: ${response.status}`);
  console.log(`message: ${await response.text()}`);
} catch (err) {
  console.error('Error sending request:', err);
} finally {
  clearTimeout(timer);
}
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
// Comma-separated, up to 100 symbols
$apiUrl = 'https://data.infoway.io/stock/batch_depth/TSLA.US,AAPL.US';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Accept: application/json',
    'apiKey: yourApikey',
]);

$response = curl_exec($ch);
if ($response === false) {
    echo 'Error sending request: ' . curl_error($ch) . PHP_EOL;
    curl_close($ch);
    exit(1);
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo "HTTP code: $httpCode" . PHP_EOL;
echo "message: $response" . PHP_EOL;
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

# Comma-separated, up to 100 symbols
api_url = 'https://data.infoway.io/stock/batch_depth/TSLA.US,AAPL.US'

headers = {
    'Accept': 'application/json',
    'apiKey': 'yourApikey',
}

response = requests.get(api_url, headers=headers, timeout=10)

print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")
```

{% endtab %}
{% endtabs %}

## Candlestick (Historical / Real-time)

`POST /stock/v2/batch_kline`

{% tabs %}
{% tab title="Go" %}

```go
package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"time"
)

func main() {
	apiURL := "https://data.infoway.io/stock/v2/batch_kline"

	// Up to 500 bars for a single symbol; when several symbols are queried at once, only the latest 2 bars are returned for each
	payload := []byte(`{"klineType":1,"klineNum":500,"codes":"TSLA.US"}`)

	req, err := http.NewRequest("POST", apiURL, bytes.NewReader(payload))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "application/json")
	req.Header.Set("apiKey", "yourApikey")

	client := &http.Client{Timeout: 10 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}

	fmt.Printf("HTTP code: %d\n", resp.StatusCode)
	fmt.Printf("message: %s\n", body)
}
```

{% endtab %}

{% tab title="Java" %}

```java
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;

public class KlineExample {
    public static void main(String[] args) throws IOException, InterruptedException {
        String apiUrl = "https://data.infoway.io/stock/v2/batch_kline";

        // Up to 500 bars for a single symbol; when several symbols are queried at once, only the latest 2 bars are returned for each
        String payload = "{\"klineType\":1,\"klineNum\":500,\"codes\":\"TSLA.US\"}";

        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();

        HttpRequest request = HttpRequest.newBuilder(URI.create(apiUrl))
                .timeout(Duration.ofSeconds(10))
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .header("apiKey", "yourApikey")
                .POST(HttpRequest.BodyPublishers.ofString(payload))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("HTTP code: " + response.statusCode());
        System.out.println("message: " + response.body());
    }
}
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
// Node.js 18+ or the browser fetch API (top-level await; save as .mjs on Node)
// Up to 500 bars for a single symbol; when several symbols are queried at once, only the latest 2 bars are returned for each
const apiUrl = 'https://data.infoway.io/stock/v2/batch_kline';

const payload = {
  klineType: 1,
  klineNum: 500,
  codes: 'TSLA.US',
};

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 10000);

try {
  const response = await fetch(apiUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      apiKey: 'yourApikey',
    },
    body: JSON.stringify(payload),
    signal: controller.signal,
  });

  console.log(`HTTP code: ${response.status}`);
  console.log(`message: ${await response.text()}`);
} catch (err) {
  console.error('Error sending request:', err);
} finally {
  clearTimeout(timer);
}
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
$apiUrl = 'https://data.infoway.io/stock/v2/batch_kline';

// Up to 500 bars for a single symbol; when several symbols are queried at once, only the latest 2 bars are returned for each
$payload = json_encode([
    'klineType' => 1,
    'klineNum'  => 500,
    'codes'     => 'TSLA.US',
]);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Accept: application/json',
    'apiKey: yourApikey',
]);

$response = curl_exec($ch);
if ($response === false) {
    echo 'Error sending request: ' . curl_error($ch) . PHP_EOL;
    curl_close($ch);
    exit(1);
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo "HTTP code: $httpCode" . PHP_EOL;
echo "message: $response" . PHP_EOL;
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

api_url = 'https://data.infoway.io/stock/v2/batch_kline'

headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'apiKey': 'yourApikey',
}

# Up to 500 bars for a single symbol; when several symbols are queried at once, only the latest 2 bars are returned for each
payload = {
    'klineType': 1,
    'klineNum': 500,
    'codes': 'TSLA.US',
}

response = requests.post(api_url, json=payload, headers=headers, timeout=10)

print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")
```

{% endtab %}
{% endtabs %}
