Statistics
  • 현재 접속자 221 명
  • 오늘 방문자 966 명
  • 어제 방문자 3,367 명
  • 최대 방문자 11,031 명
  • 전체 방문자 1,113,397 명
  • 전체 회원수 76 명
  • 전체 게시물 2,691 개
  • 전체 댓글수 4 개
AI강의사이트

비트겟(Bitget) API를 사용하여 **시세 조회(Ticker, Order Book, Market Data)**를 구현하는 Python 코드를 작성하겠습니다. --- ## **1. 주요 시세 조회 기능** 1. ✅ **현재 가격 조회 (Ticker)** 2. ✅ **호가(Or

작성자 정보

  • 작성자 bryanai
  • 작성일

컨텐츠 정보

  • 조회 413

본문

비트겟(Bitget) API를 사용하여 **시세 조회(Ticker, Order Book, Market Data)**를 구현하는 Python 코드를 작성하겠습니다.


1. 주요 시세 조회 기능

  1. 현재 가격 조회 (Ticker)
  2. 호가(Order Book) 조회
  3. 최근 거래 내역 조회 (Market Trades)

Python 코드: 비트겟 시세 조회

import requests

# === 비트겟 API 기본 설정 ===
BASE_URL = "https://api.bitget.com"
SYMBOL = "BTCUSDT"  # 조회할 거래쌍 (BTC/USDT)

# === 1️⃣ 현재 가격 조회 (Ticker) ===
def get_ticker(symbol):
    url = f"{BASE_URL}/api/v2/market/ticker"
    params = {"symbol": symbol}
    response = requests.get(url, params=params)

    if response.status_code == 200:
        data = response.json()["data"]
        print(f"✅ 현재 {symbol} 가격: {data['last']} USDT")
    else:
        print("❌ Ticker 조회 실패:", response.text)

# === 2️⃣ 호가 조회 (Order Book) ===
def get_order_book(symbol, depth=5):
    url = f"{BASE_URL}/api/v2/market/depth"
    params = {"symbol": symbol, "limit": depth}
    response = requests.get(url, params=params)

    if response.status_code == 200:
        data = response.json()["data"]
        print(f"\n {symbol} 호가(Order Book) (Top {depth})")
        print("매도(Sell) 호가:")
        for price, qty in reversed(data["asks"]):
            print(f"  가격: {price} USDT, 수량: {qty}")

        print("\n매수(Buy) 호가:")
        for price, qty in data["bids"]:
            print(f"  가격: {price} USDT, 수량: {qty}")
    else:
        print("❌ Order Book 조회 실패:", response.text)

# === 3️⃣ 최근 거래 내역 조회 (Market Trades) ===
def get_recent_trades(symbol, limit=5):
    url = f"{BASE_URL}/api/v2/market/trades"
    params = {"symbol": symbol, "limit": limit}
    response = requests.get(url, params=params)

    if response.status_code == 200:
        trades = response.json()["data"]
        print(f"\n 최근 {limit}개 거래 내역:")
        for trade in trades:
            side = "매수" if trade["side"] == "buy" else "매도"
            print(f"  가격: {trade['price']} USDT, 수량: {trade['quantity']}, 유형: {side}")
    else:
        print("❌ Market Trades 조회 실패:", response.text)

# ===  실행 ===
get_ticker(SYMBOL)
get_order_book(SYMBOL)
get_recent_trades(SYMBOL)

2. 코드 설명

1️⃣ 현재 가격 조회 (Ticker)

  • /api/v2/market/ticker
  • get_ticker(SYMBOL)
  • 결과 예시:
✅ 현재 BTCUSDT 가격: 42234.5 USDT

2️⃣ 호가 조회 (Order Book)

  • /api/v2/market/depth
  • get_order_book(SYMBOL, depth=5)
  • 결과 예시:
 BTCUSDT 호가(Order Book) (Top 5)
매도(Sell) 호가:
  가격: 42250.0 USDT, 수량: 1.2
  가격: 42248.5 USDT, 수량: 0.5
  가격: 42245.0 USDT, 수량: 0.8
  가격: 42242.0 USDT, 수량: 1.1
  가격: 42240.5 USDT, 수량: 2.0

매수(Buy) 호가:
  가격: 42230.0 USDT, 수량: 3.1
  가격: 42228.5 USDT, 수량: 0.9
  가격: 42225.0 USDT, 수량: 2.3
  가격: 42222.0 USDT, 수량: 1.5
  가격: 42220.5 USDT, 수량: 0.7

3️⃣ 최근 거래 내역 조회 (Market Trades)

  • /api/v2/market/trades
  • get_recent_trades(SYMBOL, limit=5)
  • 결과 예시:
 최근 5개 거래 내역:
  가격: 42230.0 USDT, 수량: 0.01, 유형: 매수
  가격: 42228.5 USDT, 수량: 0.05, 유형: 매도
  가격: 42225.0 USDT, 수량: 0.2, 유형: 매수
  가격: 42222.0 USDT, 수량: 0.1, 유형: 매도
  가격: 42220.5 USDT, 수량: 0.15, 유형: 매수

실행 방법

  1. Python 라이브러리 설치
pip install requests
  1. Python 코드 실행
python bitget_market_data.py

추가 기능

  • 실시간 웹소켓(WebSocket) 시세 조회 가능
  • 특정 가격대에서 알림(Alert) 설정 가능
  • 자동매매 봇과 연동 가능 (RSI/MACD)

추가 기능이 필요하면 말씀해주세요!


자바스크립트 


// === Bitget API Base Configuration ===

const BASE_URL = "https://api.bitget.com";

const SYMBOL = "BTCUSDT"; // Trading pair to query (BTC/USDT)


const fetch = require("node-fetch");


// === 1️⃣ Fetch Current Price (Ticker) ===

async function getTicker(symbol) {

    const url = `${BASE_URL}/api/v2/market/ticker?symbol=${symbol}`;


    try {

        const response = await fetch(url);

        if (response.ok) {

            const data = (await response.json()).data;

            console.log(`✅ Current ${symbol} price: ${data.last} USDT`);

        } else {

            console.error("❌ Failed to fetch ticker:", await response.text());

        }

    } catch (error) {

        console.error("❌ Error fetching ticker:", error);

    }

}


// === 2️⃣ Fetch Order Book ===

async function getOrderBook(symbol, depth = 5) {

    const url = `${BASE_URL}/api/v2/market/depth?symbol=${symbol}&limit=${depth}`;


    try {

        const response = await fetch(url);

        if (response.ok) {

            const data = (await response.json()).data;

            console.log(`\n ${symbol} Order Book (Top ${depth})`);


            console.log("Sell Orders:");

            data.asks.reverse().forEach(([price, qty]) => {

                console.log(`  Price: ${price} USDT, Quantity: ${qty}`);

            });


            console.log("\nBuy Orders:");

            data.bids.forEach(([price, qty]) => {

                console.log(`  Price: ${price} USDT, Quantity: ${qty}`);

            });

        } else {

            console.error("❌ Failed to fetch order book:", await response.text());

        }

    } catch (error) {

        console.error("❌ Error fetching order book:", error);

    }

}


// === 3️⃣ Fetch Recent Trades ===

async function getRecentTrades(symbol, limit = 5) {

    const url = `${BASE_URL}/api/v2/market/trades?symbol=${symbol}&limit=${limit}`;


    try {

        const response = await fetch(url);

        if (response.ok) {

            const trades = (await response.json()).data;

            console.log(`\n Recent ${limit} trades:`);

            trades.forEach(trade => {

                const side = trade.side === "buy" ? "Buy" : "Sell";

                console.log(`  Price: ${trade.price} USDT, Quantity: ${trade.quantity}, Type: ${side}`);

            });

        } else {

            console.error("❌ Failed to fetch recent trades:", await response.text());

        }

    } catch (error) {

        console.error("❌ Error fetching recent trades:", error);

    }

}


// === Execute ===

(async () => {

    await getTicker(SYMBOL);

    await getOrderBook(SYMBOL);

    await getRecentTrades(SYMBOL);

})();

 

관련자료

댓글 0
등록된 댓글이 없습니다.
Notice
Member Rank