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

비트겟(Bitget) API를 사용하여 **매수/매도 주문을 실행하는 Python 코드**를 작성하겠습니다. --- ## **1. 주요 기능** 1. ✅ **시장가 매수/매도 주문 실행** 2. ✅ **지정가 매수/매도 주문 실행** 3.

작성자 정보

  • 작성자 bryanai
  • 작성일

컨텐츠 정보

  • 조회 618

본문

비트겟(Bitget) API를 사용하여 매수/매도 주문을 실행하는 Python 코드를 작성하겠습니다.


1. 주요 기능

  1. 시장가 매수/매도 주문 실행
  2. 지정가 매수/매도 주문 실행
  3. 주문 상태 확인
  4. 현재 보유 잔고 조회

Python 코드: 비트겟 매수/매도 주문

import requests
import time
import hmac
import hashlib
import json

# ===  비트겟 API 정보 입력 ===
API_KEY = "your_api_key"
API_SECRET = "your_api_secret"
PASSPHRASE = "your_passphrase"
BASE_URL = "https://api.bitget.com"

# ===  서명(Signature) 생성 함수 ===
def create_signature(timestamp, method, endpoint, body=""):
    message = timestamp + method + endpoint + body
    signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
    return signature

# ===  계정 잔고 조회 함수 ===
def get_balance():
    endpoint = "/api/v2/spot/accounts"
    url = BASE_URL + endpoint
    timestamp = str(int(time.time() * 1000))  # 밀리초 단위 시간
    method = "GET"

    # 서명(Signature) 생성
    signature = create_signature(timestamp, method, endpoint)

    headers = {
        "X-BG-APIKEY": API_KEY,
        "X-BG-SIGNATURE": signature,
        "X-BG-TIMESTAMP": timestamp,
        "X-BG-PASSPHRASE": PASSPHRASE
    }

    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        print("✅ 계정 잔고 조회 성공:", response.json())
    else:
        print("❌ API 요청 실패:", response.text)

# === ✅ 시장가 주문 실행 ===
def place_market_order(symbol, side, amount):
    endpoint = "/api/v2/spot/orders"
    url = BASE_URL + endpoint
    timestamp = str(int(time.time() * 1000))  # 밀리초 단위 시간
    method = "POST"

    body = json.dumps({
        "symbol": symbol,
        "side": side,
        "type": "market",  # 시장가 주문
        "quantity": str(amount)
    })

    # 서명 생성
    signature = create_signature(timestamp, method, endpoint, body)

    headers = {
        "X-BG-APIKEY": API_KEY,
        "X-BG-SIGNATURE": signature,
        "X-BG-TIMESTAMP": timestamp,
        "X-BG-PASSPHRASE": PASSPHRASE,
        "Content-Type": "application/json"
    }

    response = requests.post(url, headers=headers, data=body)
    if response.status_code == 200:
        print("✅ 시장가 주문 성공:", response.json())
    else:
        print("❌ 주문 실패:", response.text)

# === ✅ 지정가 주문 실행 ===
def place_limit_order(symbol, side, amount, price):
    endpoint = "/api/v2/spot/orders"
    url = BASE_URL + endpoint
    timestamp = str(int(time.time() * 1000))  # 밀리초 단위 시간
    method = "POST"

    body = json.dumps({
        "symbol": symbol,
        "side": side,
        "type": "limit",  # 지정가 주문
        "price": str(price),
        "quantity": str(amount)
    })

    # 서명 생성
    signature = create_signature(timestamp, method, endpoint, body)

    headers = {
        "X-BG-APIKEY": API_KEY,
        "X-BG-SIGNATURE": signature,
        "X-BG-TIMESTAMP": timestamp,
        "X-BG-PASSPHRASE": PASSPHRASE,
        "Content-Type": "application/json"
    }

    response = requests.post(url, headers=headers, data=body)
    if response.status_code == 200:
        print("✅ 지정가 주문 성공:", response.json())
    else:
        print("❌ 주문 실패:", response.text)

# ===  주문 상태 확인 ===
def get_order_status(order_id):
    endpoint = f"/api/v2/spot/orders/{order_id}"
    url = BASE_URL + endpoint
    timestamp = str(int(time.time() * 1000))  # 밀리초 단위 시간
    method = "GET"

    signature = create_signature(timestamp, method, endpoint)

    headers = {
        "X-BG-APIKEY": API_KEY,
        "X-BG-SIGNATURE": signature,
        "X-BG-TIMESTAMP": timestamp,
        "X-BG-PASSPHRASE": PASSPHRASE
    }

    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        print("✅ 주문 상태 조회 성공:", response.json())
    else:
        print("❌ 주문 상태 조회 실패:", response.text)

# ===  실행 ===
if __name__ == "__main__":
    SYMBOL = "BTCUSDT"  # BTC/USDT 거래쌍
    TRADE_AMOUNT = 0.001  # 거래할 BTC 수량
    LIMIT_PRICE = 40000  # 지정가 주문 가격 (예제)

    # 계정 잔고 조회
    get_balance()

    # 시장가 매수 주문 실행
    place_market_order(SYMBOL, "buy", TRADE_AMOUNT)

    # 시장가 매도 주문 실행
    place_market_order(SYMBOL, "sell", TRADE_AMOUNT)

    # 지정가 매수 주문 실행
    place_limit_order(SYMBOL, "buy", TRADE_AMOUNT, LIMIT_PRICE)

    # 지정가 매도 주문 실행
    place_limit_order(SYMBOL, "sell", TRADE_AMOUNT, LIMIT_PRICE)

    # 특정 주문 상태 조회 (예제: 주문 ID를 입력)
    # get_order_status("your_order_id")

2. 코드 설명

1️⃣ 시장가 주문 실행 (Market Order)

  • place_market_order(SYMBOL, "buy", TRADE_AMOUNT) → 시장가 매수 주문
  • place_market_order(SYMBOL, "sell", TRADE_AMOUNT) → 시장가 매도 주문
  • 즉시 체결됨

2️⃣ 지정가 주문 실행 (Limit Order)

  • place_limit_order(SYMBOL, "buy", TRADE_AMOUNT, LIMIT_PRICE) → 지정가 매수 주문
  • place_limit_order(SYMBOL, "sell", TRADE_AMOUNT, LIMIT_PRICE) → 지정가 매도 주문
  • 가격이 도달해야 체결됨

3️⃣ 주문 상태 확인

  • get_order_status(order_id) → 특정 주문 ID의 상태 조회

4️⃣ 계정 잔고 확인

  • get_balance() → 현재 보유 잔고 조회

실행 방법

  1. Python 라이브러리 설치
pip install requests
  1. API Key, Secret 입력

    • API_KEY, API_SECRET, PASSPHRASE를 본인 값으로 변경
  2. Python 코드 실행

python bitget_trade.py
  1. 결과 예시
✅ 계정 잔고 조회 성공: {...}
✅ 시장가 주문 성공: {...}
✅ 지정가 주문 성공: {...}
✅ 주문 상태 조회 성공: {...}

추가 기능

  • 손절 및 익절 기능 추가 (예: -2% 손절, +5% 익절)
  • 자동매매 전략과 연동 (예: RSI, MACD 기반 매매)
  • 웹소켓(WebSocket) 기반 실시간 매매 가능

추가 기능이 필요하면 알려주세요!


자바스크립트 


// === Bitget API Info ===

const API_KEY = "your_api_key";

const API_SECRET = "your_api_secret";

const PASSPHRASE = "your_passphrase";

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


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

const crypto = require("crypto");


// === Create Signature Function ===

function createSignature(timestamp, method, endpoint, body = "") {

    const message = timestamp + method + endpoint + body;

    return crypto.createHmac("sha256", API_SECRET).update(message).digest("hex");

}


// === Get Account Balance ===

async function getBalance() {

    const endpoint = "/api/v2/spot/accounts";

    const url = `${BASE_URL}${endpoint}`;

    const timestamp = Date.now().toString();

    const method = "GET";


    const signature = createSignature(timestamp, method, endpoint);


    const headers = {

        "X-BG-APIKEY": API_KEY,

        "X-BG-SIGNATURE": signature,

        "X-BG-TIMESTAMP": timestamp,

        "X-BG-PASSPHRASE": PASSPHRASE

    };


    try {

        const response = await fetch(url, { method, headers });

        if (response.ok) {

            const data = await response.json();

            console.log("✅ Account balance fetched successfully:", data);

        } else {

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

        }

    } catch (error) {

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

    }

}


// === Place Market Order ===

async function placeMarketOrder(symbol, side, amount) {

    const endpoint = "/api/v2/spot/orders";

    const url = `${BASE_URL}${endpoint}`;

    const timestamp = Date.now().toString();

    const method = "POST";


    const body = JSON.stringify({

        symbol,

        side,

        type: "market",

        quantity: amount.toString()

    });


    const signature = createSignature(timestamp, method, endpoint, body);


    const headers = {

        "X-BG-APIKEY": API_KEY,

        "X-BG-SIGNATURE": signature,

        "X-BG-TIMESTAMP": timestamp,

        "X-BG-PASSPHRASE": PASSPHRASE,

        "Content-Type": "application/json"

    };


    try {

        const response = await fetch(url, { method, headers, body });

        if (response.ok) {

            const data = await response.json();

            console.log("✅ Market order placed successfully:", data);

        } else {

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

        }

    } catch (error) {

        console.error("❌ Error placing market order:", error);

    }

}


// === Place Limit Order ===

async function placeLimitOrder(symbol, side, amount, price) {

    const endpoint = "/api/v2/spot/orders";

    const url = `${BASE_URL}${endpoint}`;

    const timestamp = Date.now().toString();

    const method = "POST";


    const body = JSON.stringify({

        symbol,

        side,

        type: "limit",

        price: price.toString(),

        quantity: amount.toString()

    });


    const signature = createSignature(timestamp, method, endpoint, body);


    const headers = {

        "X-BG-APIKEY": API_KEY,

        "X-BG-SIGNATURE": signature,

        "X-BG-TIMESTAMP": timestamp,

        "X-BG-PASSPHRASE": PASSPHRASE,

        "Content-Type": "application/json"

    };


    try {

        const response = await fetch(url, { method, headers, body });

        if (response.ok) {

            const data = await response.json();

            console.log("✅ Limit order placed successfully:", data);

        } else {

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

        }

    } catch (error) {

        console.error("❌ Error placing limit order:", error);

    }

}


// === Get Order Status ===

async function getOrderStatus(orderId) {

    const endpoint = `/api/v2/spot/orders/${orderId}`;

    const url = `${BASE_URL}${endpoint}`;

    const timestamp = Date.now().toString();

    const method = "GET";


    const signature = createSignature(timestamp, method, endpoint);


    const headers = {

        "X-BG-APIKEY": API_KEY,

        "X-BG-SIGNATURE": signature,

        "X-BG-TIMESTAMP": timestamp,

        "X-BG-PASSPHRASE": PASSPHRASE

    };


    try {

        const response = await fetch(url, { method, headers });

        if (response.ok) {

            const data = await response.json();

            console.log("✅ Order status fetched successfully:", data);

        } else {

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

        }

    } catch (error) {

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

    }

}


// === Execute ===

(async () => {

    const SYMBOL = "BTCUSDT";

    const TRADE_AMOUNT = 0.001;

    const LIMIT_PRICE = 40000;


    await getBalance();


    await placeMarketOrder(SYMBOL, "buy", TRADE_AMOUNT);

    await placeMarketOrder(SYMBOL, "sell", TRADE_AMOUNT);


    await placeLimitOrder(SYMBOL, "buy", TRADE_AMOUNT, LIMIT_PRICE);

    await placeLimitOrder(SYMBOL, "sell", TRADE_AMOUNT, LIMIT_PRICE);


    // Example: Fetch specific order status

    // await getOrderStatus("your_order_id");

})();

 

관련자료

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