Skip to main content

One post tagged with "requests"

View All Tags

Gửi Lệnh Đặt Mua Cổ Phiếu qua API với requests

· 2 min read

Giới thiệu

Bài viết này hướng dẫn cách gửi lệnh đặt mua cổ phiếu bằng Python thông qua API sử dụng thư viện requests.

Mã nguồn

import requests

# Base URL for the API
base_url = "http://127.0.0.1:8000/newOrder" # Endpoint

# Parameters for the API request
params = {
"instrumentID": "VCB",
"market": "VN",
"buySell": "B",
"orderType": "ATO",
"price": 0,
"quantity": 100,
"account": "2654251",
"stopOrder": "false",
"stopPrice": 0,
"stopStep": 0,
"lossStep": 0,
"profitStep": 0,
"deviceId": "vEthernet (Default Switch):00-15-5D-C2-E5-EE|Wi-Fi:18-CC-18-C9-CB-6A",
"userAgent": "Python/3.11.6(Windows-10-10.0.19045-SP0); ssi-fctrading/2.4.2"
}

# Sending the GET request to the API
response = requests.get(base_url, params=params)

# Print the raw response
print(response)

# Handling the response
if response.status_code == 200:
data = response.json()["data"]
print(f"The stock order for account 2654251 is {data}")
else:
print(f"Error connecting to API: {response.status_code}")

Giải thích

  1. Import thư viện cần thiết

    • requests: Thư viện gửi HTTP request.
  2. Cấu hình API

    • base_url: Địa chỉ API xử lý lệnh đặt mua.
    • params: Các tham số truyền vào API, bao gồm mã chứng khoán, số lượng, loại lệnh, tài khoản giao dịch, v.v.
  3. Gửi yêu cầu API

    • requests.get(base_url, params=params): Gửi yêu cầu GET với các tham số đặt lệnh.
  4. Xử lý phản hồi

    • Nếu thành công (status_code == 200), lấy dữ liệu JSON và hiển thị kết quả.
    • Nếu thất bại, in thông báo lỗi với mã lỗi HTTP.

Cải tiến

Xử lý lỗi chi tiết hơn

try:
response = requests.get(base_url, params=params)
response.raise_for_status()
data = response.json().get("data", {})
print(f"Stock order response: {data}")
except requests.exceptions.RequestException as e:
print(f"API request error: {e}")

Chuyển đổi dữ liệu sang Pandas DataFrame

import pandas as pd

df = pd.DataFrame([data])
print(df.head())

Gửi lệnh bằng phương thức POST thay vì GET

response = requests.post(base_url, json=params)

📌 Tham khảo thêm: Tài liệu API đặt lệnh giao dịch