---
# System prepended metadata

title: Untitled

---

```python=
import requests
import json
import time
import csv
import hashlib
import hmac
from datetime import datetime
from apiKey import api_key, secret_key

symbol = 'BTCUSDT'  # 交易對，例如 BTCUSDT
interval = '1m'  # K 線時間間隔，例如 1m（1 分鐘）
start_time_str = '2022-01-01 00:00:00'  # 可讀的開始時間
end_time_str = '2022-01-02 01:00:00'  # 可讀的結束時間
limit = 1000  # 每次獲取的K線數量

# 建立 API 請求簽名
def create_signature(query_string):
    return hmac.new(secret_key.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()

# 發送 GET 請求
def send_get_request(url, params):
    query_string = '&'.join([f"{key}={params[key]}" for key in params])
    signature = create_signature(query_string)
    headers = {
        'X-MBX-APIKEY': api_key
    }
    response = requests.get(url + '?' + query_string + '&signature=' + signature, headers=headers)
    return response.json()

# 下載並儲存歷史資料
def download_historical_data(symbol, interval, start_time, end_time, limit):
    url = 'https://api.binance.com/api/v3/klines'
    params = {
        'symbol': symbol,
        'interval': interval,
        'startTime': start_time,
        'endTime': end_time,
        'limit': limit
    }
    response = send_get_request(url, params)

    # 檢查回應是否成功
    if 'code' in response:
        print(f"下載歷史資料時發生錯誤：{response['msg']}")
        return

    # 儲存資料到 CSV 檔案
    filename = f"{symbol}_{interval}_{start_time}_{end_time}.csv"
    with open(filename, 'w', newline='') as csvfile:
        csvwriter = csv.writer(csvfile)
        csvwriter.writerow(['Open time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close time', 'Quote asset volume', 'Number of trades', 'Taker buy base asset volume', 'Taker buy quote asset volume', 'Ignore'])
        for kline in response:
            csvwriter.writerow(kline)

    print(f"歷史資料已下載並儲存為 {filename}")

# 將可讀的時間轉換為時間戳（以毫秒為單位）
start_time = int(datetime.strptime(start_time_str, '%Y-%m-%d %H:%M:%S').timestamp() * 1000)
end_time = int(datetime.strptime(end_time_str, '%Y-%m-%d %H:%M:%S').timestamp() * 1000)

# 執行下載歷史資料的函數
download_historical_data(symbol, interval, start_time, end_time, limit)

```

![](https://hackmd.io/_uploads/Sk_L3OE8n.png)
