美國股票 API
美國上市股票及 ETF 的實時與歷史數據。
獲取全球主要市場的實時與歷史股票行情數據
美國上市股票及 ETF 的實時與歷史數據。
滬深兩市實時行情與 Level 2 深度數據。
港交所上市股票的實時與歷史數據。
東京證券交易所上市股票的實時與歷史數據。
KOSPI 與 KOSDAQ 上市股票的實時與歷史數據。
NSE 與 BSE 上市股票的實時與歷史數據。
台灣證券交易所與證券櫃枱買賣中心上市股票的實時與歷史數據。
更多市場
即將上線
註冊即用,無需綁定信用卡。
import requests
api_url = 'https://data.infoway.io/stock/v2/batch_kline'
headers = {
'User-Agent': 'Mozilla/5.0',
'Accept': 'application/json',
'Content-Type': 'application/json',
'apiKey': 'yourApikey'
}
payload = {
'klineType': 1,
'klineNum': 10,
'codes': '002594.SZ,00285.HK,TSLA.US',
}
response = requests.post(api_url, headers=headers, json=payload)
print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")import requests
api_url = "https://data.infoway.io/stock/batch_trade/002594.SZ,00285.HK,TSLA.US"
headers = {
"User-Agent": "Mozilla/5.0",
"Accept": "application/json",
"apiKey": "yourApikey",
}
response = requests.get(api_url, headers=headers)
print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")
import requests
api_url = "https://data.infoway.io/stock/batch_depth/002594.SZ,00285.HK,TSLA.US"
headers = {
"User-Agent": "Mozilla/5.0",
"Accept": "application/json",
"apiKey": "yourApikey",
}
response = requests.get(api_url, headers=headers)
print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")
import asyncio
import json
import uuid
import websockets
WS_URL = "wss://data.infoway.io/ws?business=stock&apikey=yourApikey"
async def send_heartbeat(websocket):
while True:
await asyncio.sleep(30)
ping_message = {
"code": 10010,
"trace": str(uuid.uuid4()),
}
await websocket.send(json.dumps(ping_message))
async def connect_and_receive():
async with websockets.connect(WS_URL) as websocket:
print("Connection opened")
init_message = {
"code": 10006,
"trace": str(uuid.uuid4()),
"data": {
"arr": [
{
"type": 1,
"codes": "002594.SZ,00285.HK,TSLA.US"
}
]
},
}
await websocket.send(json.dumps(init_message))
heartbeat_task = asyncio.create_task(send_heartbeat(websocket))
try:
while True:
message = await websocket.recv()
print(f"Message received: {message}")
except websockets.exceptions.ConnectionClosedOK:
print("Connection closed normally")
except websockets.exceptions.ConnectionClosed as error:
print(f"Connection closed: {error}")
finally:
heartbeat_task.cancel()
asyncio.run(connect_and_receive())
import asyncio
import json
import uuid
import websockets
WS_URL = "wss://data.infoway.io/ws?business=stock&apikey=yourApikey"
async def send_heartbeat(websocket):
while True:
await asyncio.sleep(30)
ping_message = {
"code": 10010,
"trace": str(uuid.uuid4()),
}
await websocket.send(json.dumps(ping_message))
async def connect_and_receive():
async with websockets.connect(WS_URL) as websocket:
print("Connection opened")
init_message = {
"code": 10000,
"trace": str(uuid.uuid4()),
"data": {
"codes": "002594.SZ,00285.HK,TSLA.US"
},
}
await websocket.send(json.dumps(init_message))
heartbeat_task = asyncio.create_task(send_heartbeat(websocket))
try:
while True:
message = await websocket.recv()
print(f"Message received: {message}")
except websockets.exceptions.ConnectionClosedOK:
print("Connection closed normally")
except websockets.exceptions.ConnectionClosed as error:
print(f"Connection closed: {error}")
finally:
heartbeat_task.cancel()
asyncio.run(connect_and_receive())
import asyncio
import json
import uuid
import websockets
WS_URL = "wss://data.infoway.io/ws?business=stock&apikey=yourApikey"
async def send_heartbeat(websocket):
while True:
await asyncio.sleep(30)
ping_message = {
"code": 10010,
"trace": str(uuid.uuid4()),
}
await websocket.send(json.dumps(ping_message))
async def connect_and_receive():
async with websockets.connect(WS_URL) as websocket:
print("Connection opened")
init_message = {
"code": 10003,
"trace": str(uuid.uuid4()),
"data": {
"codes": "002594.SZ,00285.HK,TSLA.US"
},
}
await websocket.send(json.dumps(init_message))
heartbeat_task = asyncio.create_task(send_heartbeat(websocket))
try:
while True:
message = await websocket.recv()
print(f"Message received: {message}")
except websockets.exceptions.ConnectionClosedOK:
print("Connection closed normally")
except websockets.exceptions.ConnectionClosed as error:
print(f"Connection closed: {error}")
finally:
heartbeat_task.cancel()
asyncio.run(connect_and_receive())
package org.example.ws;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpExample {
public static void main(String[] args) {
try {
String apiUrl = "https://data.infoway.io/stock/v2/batch_kline";
String payload = "{\"klineType\":1,\"klineNum\":10,\"codes\":\"002594.SZ,00285.HK,TSLA.US\"}";
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("apiKey","yourApikey");
try (OutputStream os = connection.getOutputStream()) {
byte[] input = payload.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
int responseCode = connection.getResponseCode();
System.out.println("HTTP code: " + responseCode);
BufferedReader reader;
if (responseCode == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println("message: " + response);
} catch (IOException e) {
e.printStackTrace();
}
}
}package org.example.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpExample {
public static void main(String[] args) {
try {
String apiUrl = "https://data.infoway.io/stock/batch_trade/002594.SZ,00285.HK,TSLA.US";
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("apiKey", "yourApikey");
int responseCode = connection.getResponseCode();
System.out.println("HTTP code: " + responseCode);
BufferedReader reader;
if (responseCode == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println("message: " + response);
} catch (IOException e) {
e.printStackTrace();
}
}
}package org.example.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpExample {
public static void main(String[] args) {
try {
String apiUrl = "https://data.infoway.io/stock/batch_depth/002594.SZ,00285.HK,TSLA.US";
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("apiKey", "yourApikey");
int responseCode = connection.getResponseCode();
System.out.println("HTTP code: " + responseCode);
BufferedReader reader;
if (responseCode == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println("message: " + response);
} catch (IOException e) {
e.printStackTrace();
}
}
}package org.example.ws;
import com.alibaba.fastjson2.JSONObject;
import jakarta.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class WebsocketExample {
private static Session session;
private static final String WS_URL = "wss://data.infoway.io/ws?business=stock&apikey=yourApikey";
public static void main(String[] args) throws Exception {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
session = container.connectToServer(WebsocketExample.MyClientEndpoint.class, URI.create(WS_URL));
session.getBasicRemote().sendText("{\"code\":10006,\"trace\":\"01213e9d-90a0-426e-a380-ebed633cba7a\",\"data\":{\"arr\":[{\"type\":1,\"codes\":\"002594.SZ,00285.HK,TSLA.US\"}]}}");
ScheduledExecutorService pingExecutor = Executors.newScheduledThreadPool(1);
pingExecutor.scheduleAtFixedRate(WebsocketExample::ping, 30, 30, TimeUnit.SECONDS);
Thread.sleep(600 * 1000);
session.close();
} catch (DeploymentException | IOException | InterruptedException e) {
e.printStackTrace();
}
}
@ClientEndpoint
public static class MyClientEndpoint {
@OnOpen
public void onOpen(Session session) {
System.out.println("Connection opened: " + session.getId());
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("Message received: " + message);
}
@OnClose
public void onClose(Session session, CloseReason reason) {
System.out.println("Connection closed: " + session.getId() + ", reason: " + reason);
}
@OnError
public void onError(Throwable error) {
error.printStackTrace();
}
}
public static void ping() {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", 10010);
jsonObject.put("trace", "01213e9d-90a0-426e-a380-ebed633cba7a");
session.getBasicRemote().sendText(jsonObject.toJSONString());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}package org.example.ws;
import com.alibaba.fastjson2.JSONObject;
import jakarta.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class WebsocketExample {
private static Session session;
private static final String WS_URL = "wss://data.infoway.io/ws?business=stock&apikey=yourApikey";
public static void main(String[] args) throws Exception {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
session = container.connectToServer(WebsocketExample.MyClientEndpoint.class, URI.create(WS_URL));
session.getBasicRemote().sendText("{\"code\":10000,\"trace\":\"01213e9d-90a0-426e-a380-ebed633cba7a\",\"data\":{\"codes\":\"002594.SZ,00285.HK,TSLA.US\"}}");
ScheduledExecutorService pingExecutor = Executors.newScheduledThreadPool(1);
pingExecutor.scheduleAtFixedRate(WebsocketExample::ping, 30, 30, TimeUnit.SECONDS);
Thread.sleep(600 * 1000);
session.close();
} catch (DeploymentException | IOException | InterruptedException e) {
e.printStackTrace();
}
}
@ClientEndpoint
public static class MyClientEndpoint {
@OnOpen
public void onOpen(Session session) {
System.out.println("Connection opened: " + session.getId());
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("Message received: " + message);
}
@OnClose
public void onClose(Session session, CloseReason reason) {
System.out.println("Connection closed: " + session.getId() + ", reason: " + reason);
}
@OnError
public void onError(Throwable error) {
error.printStackTrace();
}
}
public static void ping() {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", 10010);
jsonObject.put("trace", "01213e9d-90a0-426e-a380-ebed633cba7a");
session.getBasicRemote().sendText(jsonObject.toJSONString());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}package org.example.ws;
import com.alibaba.fastjson2.JSONObject;
import jakarta.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class WebsocketExample {
private static Session session;
private static final String WS_URL = "wss://data.infoway.io/ws?business=stock&apikey=yourApikey";
public static void main(String[] args) throws Exception {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
session = container.connectToServer(WebsocketExample.MyClientEndpoint.class, URI.create(WS_URL));
session.getBasicRemote().sendText("{\"code\":10003,\"trace\":\"01213e9d-90a0-426e-a380-ebed633cba7a\",\"data\":{\"codes\":\"002594.SZ,00285.HK,TSLA.US\"}}");
ScheduledExecutorService pingExecutor = Executors.newScheduledThreadPool(1);
pingExecutor.scheduleAtFixedRate(WebsocketExample::ping, 30, 30, TimeUnit.SECONDS);
Thread.sleep(600 * 1000);
session.close();
} catch (DeploymentException | IOException | InterruptedException e) {
e.printStackTrace();
}
}
@ClientEndpoint
public static class MyClientEndpoint {
@OnOpen
public void onOpen(Session session) {
System.out.println("Connection opened: " + session.getId());
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("Message received: " + message);
}
@OnClose
public void onClose(Session session, CloseReason reason) {
System.out.println("Connection closed: " + session.getId() + ", reason: " + reason);
}
@OnError
public void onError(Throwable error) {
error.printStackTrace();
}
}
public static void ping() {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", 10010);
jsonObject.put("trace", "01213e9d-90a0-426e-a380-ebed633cba7a");
session.getBasicRemote().sendText(jsonObject.toJSONString());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}<?php
$apiUrl = 'https://data.infoway.io/stock/v2/batch_kline';
$payload = json_encode([
'klineType' => 1,
'klineNum' => 10,
'codes' => '002594.SZ,00285.HK,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_HTTPHEADER, [
'User-Agent: Mozilla/5.0',
'Accept: application/json',
'Content-Type: application/json',
'apiKey: yourApikey'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "HTTP code: $httpCode";
echo "message: $response";
?><?php
$apiUrl = 'https://data.infoway.io/stock/batch_trade/002594.SZ,00285.HK,TSLA.US';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'User-Agent: Mozilla/5.0',
'Accept: application/json',
'apiKey: yourApikey'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "HTTP code: $httpCode\n";
echo "message: $response";
<?php
$apiUrl = 'https://data.infoway.io/stock/batch_depth/002594.SZ,00285.HK,TSLA.US';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'User-Agent: Mozilla/5.0',
'Accept: application/json',
'apiKey: yourApikey'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "HTTP code: $httpCode\n";
echo "message: $response";
<?php
require __DIR__ . '/vendor/autoload.php';
use Ratchet\Client\WebSocket;
use Ratchet\Client\Connector;
use React\EventLoop\Factory;
$loop = Factory::create();
$connector = new Connector($loop);
$wsUrl = 'wss://data.infoway.io/ws?business=stock&apikey=yourApikey';
$connector($wsUrl)->then(
function (WebSocket $conn) use ($loop) {
echo "Connection opened\n";
$conn->send('{"code":10006,"trace":"01213e9d-90a0-426e-a380-ebed633cba7a","data":{"arr":[{"type":1,"codes":"002594.SZ,00285.HK,TSLA.US"}]}}');
$loop->addPeriodicTimer(30, function () use ($conn) {
$conn->send(json_encode([
'code' => 10010,
'trace' => '01213e9d-90a0-426e-a380-ebed633cba7a',
]));
});
$conn->on('message', function ($msg) {
echo "Message received: {$msg}\n";
});
$conn->on('close', function ($code = null, $reason = null) {
echo "Connection closed ({$code}): {$reason}\n";
});
},
function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
}
);
$loop->run();
<?php
require __DIR__ . '/vendor/autoload.php';
use Ratchet\Client\WebSocket;
use Ratchet\Client\Connector;
use React\EventLoop\Factory;
$loop = Factory::create();
$connector = new Connector($loop);
$wsUrl = 'wss://data.infoway.io/ws?business=stock&apikey=yourApikey';
$connector($wsUrl)->then(
function (WebSocket $conn) use ($loop) {
echo "Connection opened\n";
$conn->send('{"code":10000,"trace":"01213e9d-90a0-426e-a380-ebed633cba7a","data":{"codes":"002594.SZ,00285.HK,TSLA.US"}}');
$loop->addPeriodicTimer(30, function () use ($conn) {
$conn->send(json_encode([
'code' => 10010,
'trace' => '01213e9d-90a0-426e-a380-ebed633cba7a',
]));
});
$conn->on('message', function ($msg) {
echo "Message received: {$msg}\n";
});
$conn->on('close', function ($code = null, $reason = null) {
echo "Connection closed ({$code}): {$reason}\n";
});
},
function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
}
);
$loop->run();
<?php
require __DIR__ . '/vendor/autoload.php';
use Ratchet\Client\WebSocket;
use Ratchet\Client\Connector;
use React\EventLoop\Factory;
$loop = Factory::create();
$connector = new Connector($loop);
$wsUrl = 'wss://data.infoway.io/ws?business=stock&apikey=yourApikey';
$connector($wsUrl)->then(
function (WebSocket $conn) use ($loop) {
echo "Connection opened\n";
$conn->send('{"code":10003,"trace":"01213e9d-90a0-426e-a380-ebed633cba7a","data":{"codes":"002594.SZ,00285.HK,TSLA.US"}}');
$loop->addPeriodicTimer(30, function () use ($conn) {
$conn->send(json_encode([
'code' => 10010,
'trace' => '01213e9d-90a0-426e-a380-ebed633cba7a',
]));
});
$conn->on('message', function ($msg) {
echo "Message received: {$msg}\n";
});
$conn->on('close', function ($code = null, $reason = null) {
echo "Connection closed ({$code}): {$reason}\n";
});
},
function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
}
);
$loop->run();
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
)
func main() {
apiUrl := "https://data.infoway.io/stock/v2/batch_kline"
payload := strings.NewReader("{\"klineType\":1,\"klineNum\":10,\"codes\":\"002594.SZ,00285.HK,TSLA.US\"}")
client := &http.Client{}
req, err := http.NewRequest("POST", apiUrl, payload)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
req.Header.Set("User-Agent", "Mozilla/5.0")
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("apiKey", "yourApikey")
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response:", err)
return
}
fmt.Printf("HTTP code:", resp.StatusCode)
fmt.Printf("message:", string(body))
}package main
import (
"fmt"
"io"
"net/http"
)
func main() {
apiUrl := "https://data.infoway.io/stock/batch_trade/002594.SZ,00285.HK,TSLA.US"
client := &http.Client{}
req, err := http.NewRequest("GET", apiUrl, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
req.Header.Set("User-Agent", "Mozilla/5.0")
req.Header.Set("Accept", "application/json")
req.Header.Set("apiKey", "yourApikey")
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.Println("HTTP code:", resp.StatusCode)
fmt.Println("message:", string(body))
}package main
import (
"fmt"
"io"
"net/http"
)
func main() {
apiUrl := "https://data.infoway.io/stock/batch_depth/002594.SZ,00285.HK,TSLA.US"
client := &http.Client{}
req, err := http.NewRequest("GET", apiUrl, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
req.Header.Set("User-Agent", "Mozilla/5.0")
req.Header.Set("Accept", "application/json")
req.Header.Set("apiKey", "yourApikey")
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.Println("HTTP code:", resp.StatusCode)
fmt.Println("message:", string(body))
}package main
import (
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"os/signal"
"syscall"
"time"
"github.com/gorilla/websocket"
)
func main() {
u := url.URL{
Scheme: "wss",
Host: "data.infoway.io",
Path: "/ws",
RawQuery: "business=stock&apikey=yourApikey",
}
log.Printf("Connecting to %s", u.String())
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
}
defer c.Close()
initMsg := []byte(`{"code":10006,"trace":"01213e9d-90a0-426e-a380-ebed633cba7a","data":{"arr":[{"type":1,"codes":"002594.SZ,00285.HK,TSLA.US"}]}}`)
if err := c.WriteMessage(websocket.TextMessage, initMsg); err != nil {
log.Fatal("write:", err)
}
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
done := make(chan struct{})
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
fmt.Println("Message received:", string(message))
}
}()
go func() {
for range ticker.C {
pingMsg := map[string]interface{}{
"code": 10010,
"trace": "01213e9d-90a0-426e-a380-ebed633cba7a",
}
pingMsgJSON, _ := json.Marshal(pingMsg)
if err := c.WriteMessage(websocket.TextMessage, pingMsgJSON); err != nil {
log.Println("ping error:", err)
return
}
}
}()
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
select {
case <-done:
log.Println("WebSocket connection closed by server")
case <-interrupt:
log.Println("Interrupted by user")
}
}package main
import (
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"os/signal"
"syscall"
"time"
"github.com/gorilla/websocket"
)
func main() {
u := url.URL{
Scheme: "wss",
Host: "data.infoway.io",
Path: "/ws",
RawQuery: "business=stock&apikey=yourApikey",
}
log.Printf("Connecting to %s", u.String())
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
}
defer c.Close()
initMsg := []byte(`{"code":10000,"trace":"01213e9d-90a0-426e-a380-ebed633cba7a","data":{"codes":"002594.SZ,00285.HK,TSLA.US"}}`)
if err := c.WriteMessage(websocket.TextMessage, initMsg); err != nil {
log.Fatal("write:", err)
}
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
done := make(chan struct{})
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
fmt.Println("Message received:", string(message))
}
}()
go func() {
for range ticker.C {
pingMsg := map[string]interface{}{
"code": 10010,
"trace": "01213e9d-90a0-426e-a380-ebed633cba7a",
}
pingMsgJSON, _ := json.Marshal(pingMsg)
if err := c.WriteMessage(websocket.TextMessage, pingMsgJSON); err != nil {
log.Println("ping error:", err)
return
}
}
}()
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
select {
case <-done:
log.Println("WebSocket connection closed by server")
case <-interrupt:
log.Println("Interrupted by user")
}
}package main
import (
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"os/signal"
"syscall"
"time"
"github.com/gorilla/websocket"
)
func main() {
u := url.URL{
Scheme: "wss",
Host: "data.infoway.io",
Path: "/ws",
RawQuery: "business=stock&apikey=yourApikey",
}
log.Printf("Connecting to %s", u.String())
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
}
defer c.Close()
initMsg := []byte(`{"code":10003,"trace":"01213e9d-90a0-426e-a380-ebed633cba7a","data":{"codes":"002594.SZ,00285.HK,TSLA.US"}}`)
if err := c.WriteMessage(websocket.TextMessage, initMsg); err != nil {
log.Fatal("write:", err)
}
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
done := make(chan struct{})
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
fmt.Println("Message received:", string(message))
}
}()
go func() {
for range ticker.C {
pingMsg := map[string]interface{}{
"code": 10010,
"trace": "01213e9d-90a0-426e-a380-ebed633cba7a",
}
pingMsgJSON, _ := json.Marshal(pingMsg)
if err := c.WriteMessage(websocket.TextMessage, pingMsgJSON); err != nil {
log.Println("ping error:", err)
return
}
}
}()
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
select {
case <-done:
log.Println("WebSocket connection closed by server")
case <-interrupt:
log.Println("Interrupted by user")
}
}const https = require('https');
const apiUrl = 'https://data.infoway.io/stock/v2/batch_kline';
const payload = JSON.stringify({
klineType: 1,
klineNum: 10,
codes: '002594.SZ,00285.HK,TSLA.US',
});
const options = {
method: 'POST',
headers: {
'User-Agent': 'Mozilla/5.0',
'Accept': 'application/json',
'Content-Type': 'application/json',
'apiKey': 'yourApikey'
}
};
const req = https.request(apiUrl, options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('HTTP code:', res.statusCode);
console.log('message:', data);
});
});
req.on('error', (error) => {
console.error('Error:', error);
});
req.write(payload);
req.end();const https = require("https");
const apiUrl = "https://data.infoway.io/stock/batch_trade/002594.SZ,00285.HK,TSLA.US";
const options = {
method: "GET",
headers: {
"User-Agent": "Mozilla/5.0",
Accept: "application/json",
apiKey: "yourApikey",
},
};
const req = https.request(apiUrl, options, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
console.log("HTTP code:", res.statusCode);
console.log("message:", data);
});
});
req.on("error", (error) => {
console.error("Error:", error);
});
req.end();
const https = require("https");
const apiUrl = "https://data.infoway.io/stock/batch_depth/002594.SZ,00285.HK,TSLA.US";
const options = {
method: "GET",
headers: {
"User-Agent": "Mozilla/5.0",
Accept: "application/json",
apiKey: "yourApikey",
},
};
const req = https.request(apiUrl, options, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
console.log("HTTP code:", res.statusCode);
console.log("message:", data);
});
});
req.on("error", (error) => {
console.error("Error:", error);
});
req.end();
const WebSocket = require("ws");
const { randomUUID } = require("crypto");
const wsUrl = "wss://data.infoway.io/ws?business=stock&apikey=yourApikey";
const ws = new WebSocket(wsUrl);
ws.on("open", () => {
console.log("Connection opened");
const initMessage = JSON.stringify({
code: 10006,
trace: randomUUID(),
data: {
"arr": [
{
"type": 1,
"codes": "002594.SZ,00285.HK,TSLA.US"
}
]
},
});
ws.send(initMessage);
const heartbeat = setInterval(() => {
if (ws.readyState !== WebSocket.OPEN) return;
ws.send(JSON.stringify({
code: 10010,
trace: randomUUID(),
}));
}, 30000);
ws.on("close", () => clearInterval(heartbeat));
});
ws.on("message", (data) => {
console.log("Message received:", data.toString());
});
ws.on("close", (code, reason) => {
console.log("Connection closed (" + code + "): " + reason);
});
ws.on("error", (error) => {
console.error("WebSocket error:", error);
});
process.on("SIGINT", () => {
ws.close();
process.exit(0);
});
const WebSocket = require("ws");
const { randomUUID } = require("crypto");
const wsUrl = "wss://data.infoway.io/ws?business=stock&apikey=yourApikey";
const ws = new WebSocket(wsUrl);
ws.on("open", () => {
console.log("Connection opened");
const initMessage = JSON.stringify({
code: 10000,
trace: randomUUID(),
data: {
"codes": "002594.SZ,00285.HK,TSLA.US"
},
});
ws.send(initMessage);
const heartbeat = setInterval(() => {
if (ws.readyState !== WebSocket.OPEN) return;
ws.send(JSON.stringify({
code: 10010,
trace: randomUUID(),
}));
}, 30000);
ws.on("close", () => clearInterval(heartbeat));
});
ws.on("message", (data) => {
console.log("Message received:", data.toString());
});
ws.on("close", (code, reason) => {
console.log("Connection closed (" + code + "): " + reason);
});
ws.on("error", (error) => {
console.error("WebSocket error:", error);
});
process.on("SIGINT", () => {
ws.close();
process.exit(0);
});
const WebSocket = require("ws");
const { randomUUID } = require("crypto");
const wsUrl = "wss://data.infoway.io/ws?business=stock&apikey=yourApikey";
const ws = new WebSocket(wsUrl);
ws.on("open", () => {
console.log("Connection opened");
const initMessage = JSON.stringify({
code: 10003,
trace: randomUUID(),
data: {
"codes": "002594.SZ,00285.HK,TSLA.US"
},
});
ws.send(initMessage);
const heartbeat = setInterval(() => {
if (ws.readyState !== WebSocket.OPEN) return;
ws.send(JSON.stringify({
code: 10010,
trace: randomUUID(),
}));
}, 30000);
ws.on("close", () => clearInterval(heartbeat));
});
ws.on("message", (data) => {
console.log("Message received:", data.toString());
});
ws.on("close", (code, reason) => {
console.log("Connection closed (" + code + "): " + reason);
});
ws.on("error", (error) => {
console.error("WebSocket error:", error);
});
process.on("SIGINT", () => {
ws.close();
process.exit(0);
});
{
"ret": 200,
"msg": "success",
"traceId": "demo",
"data": [
{
"symbol": "AAPL.US",
"periodType": "fq",
"periodDate": "2026-03-31",
"itemId": "unusual_expense_inc",
"itemName": "Unusual income/expense",
"itemGroup": "",
"itemValue": 0,
"ttm": null,
"parentItemId": "total_non_oper_income"
},
{
"symbol": "AAPL.US",
"periodType": "fq",
"periodDate": "2026-03-31",
"itemId": "total_revenue",
"itemName": "Total revenue",
"itemGroup": "",
"itemValue": 54032000000,
"ttm": 210000000000,
"parentItemId": ""
}
]
}import requests
api_url = "https://data.infoway.io/common/basic/financial/income_statement?symbol=AAPL.US&type=STOCK_US&period_type=fq"
headers = {
"User-Agent": "Mozilla/5.0",
"Accept": "application/json",
"apiKey": "yourApikey",
}
response = requests.get(api_url, headers=headers)
print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")
{
"ret": 200,
"msg": "success",
"traceId": "demo",
"data": [
{
"symbol": "AAPL.US",
"periodType": "fy",
"periodDate": "2025-12-31",
"itemId": "total_assets",
"itemName": "Total_assets",
"itemGroup": "Balance Sheet",
"itemValue": 255000000000,
"ttm": null
}
]
}import requests
api_url = "https://data.infoway.io/common/basic/financial/balance_sheet?symbol=AAPL.US&type=STOCK_US&period_type=fq"
headers = {
"User-Agent": "Mozilla/5.0",
"Accept": "application/json",
"apiKey": "yourApikey",
}
response = requests.get(api_url, headers=headers)
print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")
{
"ret": 200,
"msg": "success",
"traceId": "demo",
"data": [
{
"symbol": "AAPL.US",
"periodType": "fq",
"periodDate": "2025-12-31",
"itemId": "cf_oper",
"itemName": "Cf_oper",
"itemGroup": "Cash Flow Statement",
"itemValue": 25000000000,
"ttm": null
}
]
}import requests
api_url = "https://data.infoway.io/common/basic/financial/cash_flow?symbol=AAPL.US&type=STOCK_US&period_type=fq"
headers = {
"User-Agent": "Mozilla/5.0",
"Accept": "application/json",
"apiKey": "yourApikey",
}
response = requests.get(api_url, headers=headers)
print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")
{
"ret": 200,
"msg": "success",
"traceId": "demo",
"data": [
{
"symbol": "AAPL.US",
"periodType": "fy",
"periodDate": "2024",
"itemId": "product_iphone",
"itemName": "Product_iphone",
"itemGroup": "Revenue by business",
"itemValue": 200583000000,
"ttm": null
}
]
}import requests
api_url = "https://data.infoway.io/common/basic/financial/revenue?symbol=AAPL.US&type=STOCK_US&period_type=fy"
headers = {
"User-Agent": "Mozilla/5.0",
"Accept": "application/json",
"apiKey": "yourApikey",
}
response = requests.get(api_url, headers=headers)
print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")
{
"ret": 200,
"msg": "success",
"traceId": "demo",
"data": [
{
"symbol": "AAPL.US",
"periodType": "fq",
"periodDate": "2025-12-31",
"itemId": "pe_ratio",
"itemName": "Pe_ratio",
"itemGroup": "Valuation ratios",
"itemValue": 25.5,
"ttmStr": "24.8",
"currentValue": 26.1
}
]
}import requests
api_url = "https://data.infoway.io/common/basic/financial/statistics?symbol=AAPL.US&type=STOCK_US&period_type=fq"
headers = {
"User-Agent": "Mozilla/5.0",
"Accept": "application/json",
"apiKey": "yourApikey",
}
response = requests.get(api_url, headers=headers)
print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")
{
"ret": 200,
"msg": "success",
"traceId": "demo",
"data": [
{
"symbol": "AAPL.US",
"periodType": "fy",
"periodDate": "2025-12-31",
"itemId": "dividend_yield",
"itemName": "Dividend_yield",
"itemGroup": "Dividend",
"itemValue": 1.25,
"ttmStr": "1.30",
"currentValue": 1.28
}
]
}import requests
api_url = "https://data.infoway.io/common/basic/financial/dividend?symbol=AAPL.US&type=STOCK_US&period_type=fq"
headers = {
"User-Agent": "Mozilla/5.0",
"Accept": "application/json",
"apiKey": "yourApikey",
}
response = requests.get(api_url, headers=headers)
print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")
{
"ret": 200,
"msg": "success",
"traceId": "demo",
"data": [
{
"symbol": "AAPL.US",
"exDate": 1747267200000,
"recordDate": 1747353600000,
"paymentDate": 1747948800000,
"amount": 0.26,
"type": "quarterly"
}
]
}import requests
api_url = "https://data.infoway.io/common/basic/financial/dividend_payout?symbol=AAPL.US&type=STOCK_US"
headers = {
"User-Agent": "Mozilla/5.0",
"Accept": "application/json",
"apiKey": "yourApikey",
}
response = requests.get(api_url, headers=headers)
print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")
{
"ret": 200,
"msg": "success",
"traceId": "demo",
"data": [
{
"symbol": "AAPL.US",
"periodType": "fq",
"periodKey": "2026-Q1",
"epsActual": 1.65,
"epsEstimate": 1.62,
"epsPercentage": 1.85,
"revenueActual": 124300000000,
"revenueEstimate": 122500000000,
"revenuePercentage": 1.47
}
]
}import requests
api_url = "https://data.infoway.io/common/basic/financial/earnings?symbol=AAPL.US&type=STOCK_US&period_type=fq"
headers = {
"User-Agent": "Mozilla/5.0",
"Accept": "application/json",
"apiKey": "yourApikey",
}
response = requests.get(api_url, headers=headers)
print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")
為金融應用設計的結構化公司數據,幫你做出內容豐富、吸引用戶的個股頁面。
以及更多...
開始免費試用很多股票 API 只覆蓋單一國家,海外市場只提供延時數據。Infoway 覆蓋的每個市場都是實時行情,一個 API 全部接入。
一個 API Key、一套代碼格式、一套數據結構,實時接入多市場的股票行情。
通過 WebSocket 訂閱一次,每筆成交和盤口變化都會實時推送。無需輪詢,也不用擔心頻率限制。
所有市場都提供買一賣一;部分市場提供完整的 Level 2 盤口。深度圖、交易工具和價差監控,都能用同一條數據流實現。
提供 1 分鐘到月線的歷史 K 線:分鐘和小時 K 線按套餐最長可回溯 3 年,日線及以上提供完整歷史。回溯和實盤用同一套代碼和數據格式。
同一個 API、同一個套餐還包含外匯、加密貨幣和商品期貨,數據格式和 WebSocket 推送完全一致。
7 天內免費體驗所有市場的實時行情、成交和盤口,無需綁定信用卡。先在自己的應用裡看到數據,再決定選哪個套餐。
為你的金融產品、交易策略、研究和工作流提供數據。
拉取一年的日 K 線,用幾行 Python 計算均線,測試金叉策略。
import pandas as pd
import requests
URL = "https://data.infoway.io/stock/v2/batch_kline"
HEADERS = {"apiKey": "YOUR_API_KEY"}
payload = {"klineType": 8, "klineNum": 270, "codes": "AAPL.US"} # 270 daily candles
resp = requests.post(URL, headers=HEADERS, json=payload, timeout=10).json()
bars = resp["data"][0]["respList"] # newest first
df = pd.DataFrame(bars)
df["t"] = pd.to_datetime(df["t"].astype(int), unit="s")
df = df.set_index("t").sort_index() # oldest first, so averages look back in time
df["c"] = df["c"].astype(float)
df["sma20"] = df["c"].rolling(20).mean()
df["sma50"] = df["c"].rolling(50).mean()
above = df["sma20"] > df["sma50"]
golden_cross = above & ~above.shift(1, fill_value=True) # 20-day crosses above 50-day
print("Golden crosses:", list(df.index[golden_cross].date))
print("20-day above 50-day now:", bool(above.iloc[-1]))通過 WebSocket 訂閱一次,行情變化直接推送到你的報價列表或下單介面,無需輪詢。
import asyncio
import json
import uuid
import requests
import websockets
API_KEY = "YOUR_API_KEY"
REST_URL = "https://data.infoway.io/stock/v2/batch_kline"
WS_URL = f"wss://data.infoway.io/ws?business=stock&apikey={API_KEY}"
SYMBOLS = "AAPL.US,MSFT.US,NVDA.US"
def frame(code, data=None):
msg = {"code": code, "trace": uuid.uuid4().hex}
if data is not None:
msg["data"] = data
return json.dumps(msg)
def update_price_row(symbol, price, change, change_pct):
print(f"{symbol:<8} {price:>10.2f} {change:>+8.2f} {change_pct}") # push into your quote grid
def load_snapshot():
"""Show the latest price right away, even when the market is closed."""
body = {"klineType": 8, "klineNum": 1, "codes": SYMBOLS}
resp = requests.post(REST_URL, headers={"apiKey": API_KEY}, json=body, timeout=10).json()
for item in resp["data"]:
bar = item["respList"][0]
update_price_row(item["s"], float(bar["c"]), float(bar["pca"]), bar["pc"])
async def heartbeat(ws):
while True:
await asyncio.sleep(30)
await ws.send(frame(10010))
async def ticker_tape():
while True:
try:
load_snapshot()
async with websockets.connect(WS_URL) as ws:
# daily candles carry the last price and the change vs the previous close
await ws.send(frame(10006, {"arr": [{"type": 8, "codes": SYMBOLS}]}))
hb = asyncio.create_task(heartbeat(ws))
try:
async for raw in ws:
try:
msg = json.loads(raw)
except ValueError:
continue # skip plain-text notices from the server
if msg.get("code") == 10008: # candle push
d = msg["data"]
update_price_row(d["s"], float(d["c"]), float(d["pca"]), d["pfr"])
finally:
hb.cancel()
except (websockets.ConnectionClosed, OSError, requests.RequestException):
await asyncio.sleep(5) # back off before reconnecting
asyncio.run(ticker_tape())
如需幫助,請隨時聯絡客服。
可以。每個新帳戶都有 7 天免費試用,包含實時行情、K 線、逐筆成交和盤口數據,以及最近 6 個月的歷史數據,無需綁定信用卡。免費試用只能查詢部分品種,具體見免費試用品種列表。
所有支援的市場都是實時行情。
美股、A股(上交所、深交所)、港股(港交所)、日股(東京證券交易所)、韓股(韓國交易所)、印度股票(NSE、BSE)和台股(台灣證交所、櫃買中心)。
歷史 K 線最細到 1 分鐘。分鐘和小時 K 線的可查範圍按套餐而定:基礎版 1 年,專業版 3 年,免費試用為最近 6 個月。日線及以上週期,所有套餐都提供完整歷史。
支援。每個帳戶最多可訂閱 5,000 個品種,成交實時推送。
任何能發送 HTTP 或 WebSocket 請求的語言都可以。官方提供 Python、Java、Go 和 JavaScript SDK。
可以。品種列表每天更新,新股上市當天即可獲取,退市股票會自動移除。

