iT邦幫忙

2024 iThome 鐵人賽

DAY 24
0
AI/ ML & Data

自動交易程式探索系列 第 24

Day 24 - 完整的幣安現貨買賣下單程式

  • 分享至 

  • xImage
  •  

之後要寫一個完整的自動交易機器人,所以我這邊先把現貨交易需要用到的功能都預先寫好,這樣之後方便使用。
開發過程中,有碰到一些小問題,特別是在掛單的最小交易數量、最小交易額(notional)上面,因此這邊多寫了一點筆記:

最小交易數量與步進大小

在幣安的 API 中,每個交易對都有特定的規則,比如最小交易數量(lot size)和步進大小(step size)。這些規則會直接影響我們能夠下單的最小數量。當初,我在寫掛單功能時,忽略了這個細節,導致掛單時出現了 Filter failure: LOT_SIZE 的錯誤提示。這提示說明我掛的單子未滿足交易對的最小數量要求。

為了修正這個問題,我專門寫了一個函數來查詢交易對的最小交易數量和步進大小。這樣,我可以在下單之前先確認訂單的數量是否符合要求:

def get_lot_size_and_step_size(self, symbol):
    info = self.client.get_symbol_info(symbol)
    lot_size, step_size = None, None
    for f in info['filters']:
        if f['filterType'] == 'LOT_SIZE':
            lot_size = float(f['minQty'])
            step_size = float(f['stepSize'])
    return lot_size, step_size

這個函數幫助我解決了大部分的 LOT_SIZE 問題。在掛單時,我會先查詢最小交易數量,然後對即將掛單的數量進行校準,確保其符合規則。

最小名義價值 (Notional)

在處理限價掛單時,我還發現一個 NOTIONAL 的問題。幣安要求每筆交易的名義價值必須大於某個門檻(通常是10美元)。當我最開始忽略這個規則時,掛單會因為未滿足最小名義價值而失敗。後來我加入了對 MIN_NOTIONAL 的檢查,並寫了一個函數來計算滿足最小交易金額限制。

這段代碼展示了如何計算最小的掛單數量,確保它滿足最小交易金額限制的要求:

def calculate_min_order_quantity(self, price, lot_size, step_size, min_notional):
    min_quantity_by_notional = min_notional / price
    rounded_quantity = round((min_quantity_by_notional // step_size) * step_size, len(str(step_size).split('.')[1]))
    
    if rounded_quantity < lot_size:
        rounded_quantity = lot_size
    
    while rounded_quantity * price < min_notional:
        rounded_quantity += step_size
        rounded_quantity = round(rounded_quantity, len(str(step_size).split('.')[1]))
    
    return rounded_quantity

這個功能讓我可以動態調整訂單數量,從而保證每筆掛單不會因為價值過低而被拒絕。

處理限價單

我在實現限價單的過程中還遇到了另一個挑戰:限價單不會立即成交,它會掛在市場上直到成交或被取消。為了更好地控制這類訂單,我加入了查詢和取消訂單的功能。

在每次掛單之後,我會查詢該訂單的狀態,並根據需要選擇是否取消該訂單。這使得我能夠在測試過程中隨時調整掛單,避免因掛單持續未成交而占用資金。

def cancel_order(self, symbol, order_id):
    try:
        result = self.client.cancel_order(symbol=symbol, orderId=order_id)
        return result
    except Exception as e:
        return None

這個功能確保了我能在掛單出現問題或需要調整時迅速撤單,而不會導致不必要的損失。

完整的幣安現貨自動下單程式:
這邊交易對可以視自己的需求修改。

if __name__ == "__main__":
    ...
    asset = 'BNB'
    quote_asset = 'USDC'
    ...
from binance.client import Client
from binance.enums import *
import datetime

class SpotTrading:
    def __init__(self, api_key, api_secret):
        # 創建 Binance 客戶端
        self.client = Client(api_key, api_secret)

    def logger(self, message):
        # 簡單的log函數,記錄時間並打印出消息
        timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print(f"[{timestamp}] {message}")

    def get_symbol_info(self, symbol):
        # 查詢交易對的完整資訊,包括基礎資產和報價資產
        self.logger(f"Fetching symbol info for: {symbol}")
        info = self.client.get_symbol_info(symbol)
        if info is None:
            raise ValueError(f"Symbol {symbol} not found.")
        base_asset = info['baseAsset']
        quote_asset = info['quoteAsset']
        self.logger(f"Symbol info - Base Asset: {base_asset}, Quote Asset: {quote_asset}")
        return base_asset, quote_asset, info

    def get_asset_balance(self, asset):
        # 取得指定資產的餘額
        self.logger(f"Fetching balance for asset: {asset}")
        balance = self.client.get_asset_balance(asset=asset)
        self.logger(f"Balance for {asset}: {balance['free']} (Free), {balance['locked']} (Locked)")
        return float(balance['free'])

    def get_lot_size_and_step_size(self, symbol):
        base_asset, quote_asset, symbol_info = self.get_symbol_info(symbol)
        # 查詢交易對的最小訂單數量和步進大小
        self.logger(f"Fetching lot size and step size from symbol info.")
        lot_size, step_size = None, None
        for f in symbol_info['filters']:
            if f['filterType'] == 'LOT_SIZE':
                lot_size = float(f['minQty'])
                step_size = float(f['stepSize'])
        self.logger(f"Lot Size: {lot_size}, Step Size: {step_size}")
        return lot_size, step_size
        
    def get_min_notional(self, symbol):
        base_asset, quote_asset, symbol_info = self.get_symbol_info(symbol)
        # 查詢交易對的最小名義價值限制
        self.logger(f"Fetching min notional from symbol info.")
        min_notional = None
        for f in symbol_info['filters']:
            if f['filterType'] == 'MIN_NOTIONAL':
                min_notional = float(f['minNotional'])

        if min_notional is not None:
            self.logger(f"Min Notional: {min_notional}")
        else:
            self.logger(f"No min notional found, using default value of 10.")
            min_notional = 10  # 默認值為 10 美元

        return min_notional

    def round_quantity(self, quantity, step_size):
        # 根據 step_size 進行下捨,並將精度限制為小數點位數
        precision = len(str(step_size).split('.')[1])
        rounded_quantity = round((quantity // step_size) * step_size, precision)
        self.logger(f"Rounded quantity: {rounded_quantity} (Original: {quantity}, Step Size: {step_size})")
        return rounded_quantity
        
    def calculate_min_order_quantity(self, price, lot_size, step_size, min_notional):
        # 計算滿足所有條件的最小掛單數量
        self.logger(f"Calculating minimum order quantity for price: {price}, lot size: {lot_size}, step size: {step_size}, min notional: {min_notional}")
        
        # 首先計算滿足最小notional要求的數量
        min_quantity_by_notional = min_notional / price
        
        # 將數量向上調整,滿足step_size的要求
        precision = len(str(step_size).split('.')[1])
        rounded_quantity = round((min_quantity_by_notional // step_size) * step_size, precision)
        
        # 確保最小數量同時滿足lot_size的要求
        if rounded_quantity < lot_size:
            rounded_quantity = lot_size
        
        # 檢查舍入後的數量是否仍然滿足min_notional的要求
        while rounded_quantity * price < min_notional:
            rounded_quantity += step_size
            rounded_quantity = round(rounded_quantity, precision)
        
        self.logger(f"Calculated minimum order quantity: {rounded_quantity}")
        return rounded_quantity


    def buy_asset(self, asset, symbol, quantity, price=None):
        # 買入指定數量的資產,支持市價單和限價單
        if price is None:
            self.logger(f"Placing market buy order for {quantity} {asset} on symbol {symbol}")
            try:
                order = self.client.order_market_buy(
                    symbol=symbol,
                    quantity=quantity  # 使用指定的資產數量
                )
                self.logger(f"Market Buy Order Executed: {order}")
                return order
            except Exception as e:
                self.logger(f"Error executing market buy order: {e}")
                return None
        else:
            self.logger(f"Placing limit buy order for {quantity} {asset} at price {price} on symbol {symbol}")
            try:
                order = self.client.order_limit_buy(
                    symbol=symbol,
                    quantity=quantity,
                    price=str(price)  # 使用指定的資產數量與價格
                )
                self.logger(f"Limit Buy Order Executed: {order}")
                return order
            except Exception as e:
                self.logger(f"Error executing limit buy order: {e}")
                return None

    def sell_asset(self, asset, symbol, quantity, price=None):
        # 賣出指定數量的資產,支持市價單和限價單
        if price is None:
            self.logger(f"Placing market sell order for {quantity} {asset} on symbol {symbol}")
            try:
                order = self.client.order_market_sell(
                    symbol=symbol,
                    quantity=quantity  # 使用指定的資產數量
                )
                self.logger(f"Market Sell Order Executed: {order}")
                return order
            except Exception as e:
                self.logger(f"Error executing market sell order: {e}")
                return None
        else:
            self.logger(f"Placing limit sell order for {quantity} {asset} at price {price} on symbol {symbol}")
            try:
                order = self.client.order_limit_sell(
                    symbol=symbol,
                    quantity=quantity,
                    price=str(price)  # 使用指定的資產數量與價格
                )
                self.logger(f"Limit Sell Order Executed: {order}")
                return order
            except Exception as e:
                self.logger(f"Error executing limit sell order: {e}")
                return None

    def cancel_order(self, symbol, order_id):
        # 取消指定的訂單
        self.logger(f"Canceling order {order_id} on symbol {symbol}")
        try:
            result = self.client.cancel_order(
                symbol=symbol,
                orderId=order_id
            )
            self.logger(f"Order {order_id} canceled successfully: {result}")
            return result
        except Exception as e:
            self.logger(f"Error canceling order {order_id}: {e}")
            return None

    def get_open_orders(self, symbol=None):
        # 查詢所有開啟的掛單
        self.logger(f"Fetching open orders for symbol: {symbol if symbol else 'all symbols'}")
        try:
            if symbol:
                orders = self.client.get_open_orders(symbol=symbol)
            else:
                orders = self.client.get_open_orders()
            self.logger(f"Open Orders: {orders}")
            return orders
        except Exception as e:
            self.logger(f"Error fetching open orders: {e}")
            return None

    def get_order_status(self, symbol, order_id):
        # 查詢指定的訂單狀態
        self.logger(f"Fetching status for order {order_id} on symbol {symbol}")
        try:
            order = self.client.get_order(
                symbol=symbol,
                orderId=order_id
            )
            self.logger(f"Order Status: {order}")
            return order
        except Exception as e:
            self.logger(f"Error fetching order status: {e}")
            return None

    def get_current_price(self, symbol):
        # 查詢市場價格
        self.logger(f"Fetching current price for symbol: {symbol}")
        ticker = self.client.get_symbol_ticker(symbol=symbol)
        current_price = float(ticker['price'])
        self.logger(f"Current price for {symbol}: {current_price}")
        return current_price

    def buy_all_asset(self, asset, symbol):
        # 自動提取報價資產(如 USDT/BUSD),使用報價資產購買基礎資產
        base_asset, quote_asset, symbol_info = self.get_symbol_info(symbol)
        
        # 使用報價資產的餘額進行購買
        self.logger(f"Buying all available {base_asset} using {quote_asset}")
        quote_balance = self.get_asset_balance(quote_asset)

        lot_size, step_size = self.get_lot_size_and_step_size(symbol)
        current_price = self.get_current_price(symbol)
        estimated_quantity = quote_balance / current_price
        estimated_quantity_rounded = self.round_quantity(estimated_quantity, step_size)

        return self.buy_asset(base_asset, symbol, estimated_quantity_rounded)

    def sell_all_asset(self, asset, symbol):
        # 自動提取報價資產(如 USDT/BUSD),賣出基礎資產
        base_asset, quote_asset, symbol_info = self.get_symbol_info(symbol)

        self.logger(f"Selling all available {base_asset} for {quote_asset}")
        base_balance = self.get_asset_balance(base_asset)

        lot_size, step_size = self.get_lot_size_and_step_size(symbol)
        base_quantity_rounded = self.round_quantity(base_balance, step_size)

        return self.sell_asset(base_asset, symbol, base_quantity_rounded)

    def print_balances(self, asset, quote_asset='USDT'):
        # 取得並印出指定資產和 quote_asset 的餘額
        self.logger(f"Printing balances for {asset} and {quote_asset}")
        asset_balance = self.get_asset_balance(asset)
        quote_asset_balance = self.get_asset_balance(quote_asset)

        self.logger(f"{asset} Balance: {asset_balance}")
        self.logger(f"{quote_asset} Balance: {quote_asset_balance}")

    def get_order_book(self, symbol, limit=5):
        # 查詢交易對的訂單簿深度
        self.logger(f"Fetching order book for symbol: {symbol} with limit {limit}")
        order_book = self.client.get_order_book(symbol=symbol, limit=limit)
        return order_book

    def print_order_book(self, symbol, limit=5):
        # 印出訂單簿深度
        self.logger(f"Printing order book for symbol: {symbol}")
        order_book = self.get_order_book(symbol, limit)
        print(f"Order Book (Top {limit} Levels):")

        print("Bids (Buy Orders):")
        for bid in order_book['bids']:
            print(f"Price: {bid[0]}, Quantity: {bid[1]}")

        print("\nAsks (Sell Orders):")
        for ask in order_book['asks']:
            print(f"Price: {ask[0]}, Quantity: {ask[1]}")


def wait_for_keypress(title=None):
    if title is not None and type(title) == str:
        input(title)
    else:
        input("按下任意鍵繼續...")
    
# 使用範例
if __name__ == "__main__":
    # 創建交易物件
    from config import API_KEY, API_SECRET
    trader = SpotTrading(API_KEY, API_SECRET)
    
    asset = 'BNB'
    quote_asset = 'USDC'
    symbol = f'{asset}{quote_asset}'
    
    wait_for_keypress(f"""
    此範例將執行以下操作:
    1. 先查詢當前 {asset} 與 {quote_asset} 的餘額,並顯示最新的訂單簿資料。
    2. 在查詢到最新的市場價格後,將以市場價格加上 $50 的限價掛單售賣最小可交易的 {asset} 數量(根據幣安的規則,考慮到最小名義價值和訂單精度)。
    3. 掛單後,將查詢該訂單的狀態,若掛單成功,將提供選項來取消該訂單。
    4. 隨後,將以市場價格賣出帳戶內所有的 {asset}。
    5. 在成功賣出所有 {asset} 後,會再以市場價格花光所有 {quote_asset} 購買 {asset}。
    6. 購買完成後,將再次顯示當前的 {asset} 與 {quote_asset} 餘額。

    請注意,此範例將會賣出您帳戶內的所有 {asset},並使用所有的 {quote_asset} 來購買 {asset}。請確保您帳戶內的資金配置可供實驗,並注意此範例可能會影響您的實際資金。
    按下 Enter 以開始執行該範例操作:
    """)

    # 查詢訂單簿
    print("\nOrder Book:")
    trader.print_order_book(symbol)

    # 印出當前餘額
    print(f"Balances before trading {asset}:")
    trader.print_balances(asset, quote_asset)

    symbol_lot_size, symbol_step_size = trader.get_lot_size_and_step_size(symbol)
    min_notional = trader.get_min_notional(symbol)

    # 限價賣單範例
    current_price = trader.get_current_price(symbol)
    order_price = current_price+50
    order_quantity = trader.calculate_min_order_quantity(order_price, symbol_lot_size, symbol_step_size, min_notional)
    wait_for_keypress(f"按下Enter後, 以{order_price}的價格, 在交易對{symbol}上掛限價賣單, 售賣{order_quantity}顆{asset}")
    order = trader.sell_asset(asset, symbol, quantity=order_quantity, price=order_price)
    if order:
        # 查詢訂單狀態
        order_status = trader.get_order_status(symbol, order['orderId'])
        print(f"Order Status: {order_status}")
        
        # 查詢當前所有掛單
        open_orders = trader.get_open_orders(symbol)
        print(f"Open Orders: {open_orders}")
        
        if order_status['isWorking']:
            wait_for_keypress("按下Enter後取消此限價賣單")
        else:
            print("限價賣單掛單失敗")

        # 嘗試取消限價賣單
        trader.cancel_order(symbol, order['orderId'])
        
    wait_for_keypress(f"按下Enter後, 將以市價賣出所有{symbol}")
        
    # 賣出所有的資產 (市價單)
    trader.sell_all_asset(asset, symbol)

    # 再次印出餘額
    print(f"\nbalances after selling {asset}:")
    trader.print_balances(asset, quote_asset)

    # 限價買單範例
    current_price = trader.get_current_price(symbol)
    order_price = current_price-50
    order_quantity = trader.calculate_min_order_quantity(order_price, symbol_lot_size, symbol_step_size, min_notional)
    wait_for_keypress(f"按下Enter後, 以{order_price}的價格, 在交易對{symbol}上掛限價買單, 購買{order_quantity}顆{asset}")
    order = trader.buy_asset(asset, symbol, quantity=order_quantity, price=order_price)
    if order:
        # 查詢訂單狀態
        order_status = trader.get_order_status(symbol, order['orderId'])
        print(f"Order Status: {order_status}")
        
        # 查詢當前所有掛單
        open_orders = trader.get_open_orders(symbol)
        print(f"Open Orders: {open_orders}")
        
        if order_status['isWorking']:
            wait_for_keypress("按下Enter後取消此限價買單")
        else:
            print("限價買單掛單失敗")

        # 嘗試取消限價買單
        trader.cancel_order(symbol, order['orderId'])
        
    wait_for_keypress(f"按下Enter後, 將以市價花光所有{quote_asset}買入{symbol}")

    # 使用所有 quote_asset 購買資產 (市價單)
    trader.buy_all_asset(asset, symbol)

    # 再次印出餘額
    print(f"\nbalances after buying {asset}:")
    trader.print_balances(asset, quote_asset)

python spottrading.py執行結果如下:
其實從訂單簿(LOB)可以看出USDC的深度真的很差,自動交易還是要用USDT比較方便,不過這個自己改就好,範例還是使用USDC

這邊有把訂單狀態的細節隱藏,以免有些安全上的問題。

    此範例將執行以下操作:
    1. 先查詢當前 BNB 與 USDC 的餘額,並顯示最新的訂單簿資料。
    2. 在查詢到最新的市場價格後,將以市場價格加上 $50 的限價掛單售賣最小可交易的 BNB 數量(根據幣安的規則,考慮到最小名 義價值和訂單精度)。
    3. 掛單後,將查詢該訂單的狀態,若掛單成功,將提供選項來取消該訂單。
    4. 隨後,將以市場價格賣出帳戶內所有的 BNB。
    5. 在成功賣出所有 BNB 後,會再以市場價格花光所有 USDC 購買 BNB。
    6. 購買完成後,將再次顯示當前的 BNB 與 USDC 餘額。

    請注意,此範例將會賣出您帳戶內的所有 BNB,並使用所有的 USDC 來購買 BNB。請確保您帳戶內的資金配置可供實驗,並注意此範例可能會影響您的實際資金。
    按下 Enter 以開始執行該範例操作:


Order Book:
[2024-10-08 02:16:29] Printing order book for symbol: BNBUSDC
[2024-10-08 02:16:29] Fetching order book for symbol: BNBUSDC with limit 5
Order Book (Top 5 Levels):
Bids (Buy Orders):
Price: 573.10000000, Quantity: 7.81300000
Price: 573.00000000, Quantity: 7.52100000
Price: 572.90000000, Quantity: 1.29100000
Price: 572.80000000, Quantity: 1.41900000
Price: 572.70000000, Quantity: 0.46500000

Asks (Sell Orders):
Price: 573.30000000, Quantity: 12.93400000
Price: 573.40000000, Quantity: 4.88200000
Price: 573.50000000, Quantity: 4.87700000
Price: 573.60000000, Quantity: 2.60600000
Price: 573.70000000, Quantity: 0.33600000
Balances before trading BNB:
[2024-10-08 02:16:30] Printing balances for BNB and USDT
[2024-10-08 02:16:30] Fetching balance for asset: BNB
[2024-10-08 02:16:30] Balance for BNB: 0.02624832 (Free), 0.00000000 (Locked)
[2024-10-08 02:16:30] Fetching balance for asset: USDT
[2024-10-08 02:16:30] Balance for USDT: 0.01760000 (Free), 0.00000000 (Locked)
[2024-10-08 02:16:30] BNB Balance: 0.02624832
[2024-10-08 02:16:30] USDT Balance: 0.0176
[2024-10-08 02:16:30] Fetching symbol info for: BNBUSDC
[2024-10-08 02:16:30] Symbol info - Base Asset: BNB, Quote Asset: USDC
[2024-10-08 02:16:30] Fetching lot size and step size from symbol info.
[2024-10-08 02:16:30] Lot Size: 0.001, Step Size: 0.001
[2024-10-08 02:16:30] Fetching symbol info for: BNBUSDC
[2024-10-08 02:16:30] Symbol info - Base Asset: BNB, Quote Asset: USDC
[2024-10-08 02:16:30] Fetching min notional from symbol info.
[2024-10-08 02:16:30] No min notional found, using default value of 10.
[2024-10-08 02:16:30] Fetching current price for symbol: BNBUSDC
[2024-10-08 02:16:30] Current price for BNBUSDC: 573.1
[2024-10-08 02:16:30] Calculating minimum order quantity for price: 623.1, lot size: 0.001, step size: 0.001, min notional: 10
[2024-10-08 02:16:30] Calculated minimum order quantity: 0.017
按下Enter後, 以623.1的價格, 在交易對BNBUSDC上掛限價賣單, 售賣0.017顆BNB
[2024-10-08 02:16:50] Placing limit sell order for 0.017 BNB at price 623.1 on symbol BNBUSDC
[2024-10-08 02:16:50] Limit Sell Order Executed: {...}
[2024-10-08 02:16:50] Fetching status for order 426065403 on symbol BNBUSDC
[2024-10-08 02:16:50] Order Status: {...}
Order Status: {...}
[2024-10-08 02:16:50] Fetching open orders for symbol: BNBUSDC
[2024-10-08 02:16:50] Open Orders: [{...}]
Open Orders: [{...}]
按下Enter後取消此限價賣單
[2024-10-08 02:16:59] Canceling order 426065403 on symbol BNBUSDC
[2024-10-08 02:16:59] Order 426065403 canceled successfully: {...}
按下Enter後, 將以市價賣出所有BNBUSDC
[2024-10-08 02:17:04] Fetching symbol info for: BNBUSDC
[2024-10-08 02:17:05] Symbol info - Base Asset: BNB, Quote Asset: USDC
[2024-10-08 02:17:05] Selling all available BNB for USDC
[2024-10-08 02:17:05] Fetching balance for asset: BNB
[2024-10-08 02:17:05] Balance for BNB: 0.02624832 (Free), 0.00000000 (Locked)
[2024-10-08 02:17:05] Fetching symbol info for: BNBUSDC
[2024-10-08 02:17:05] Symbol info - Base Asset: BNB, Quote Asset: USDC
[2024-10-08 02:17:05] Fetching lot size and step size from symbol info.
[2024-10-08 02:17:05] Lot Size: 0.001, Step Size: 0.001
[2024-10-08 02:17:05] Rounded quantity: 0.026 (Original: 0.02624832, Step Size: 0.001)
[2024-10-08 02:17:05] Placing market sell order for 0.026 BNB on symbol BNBUSDC
[2024-10-08 02:17:05] Market Sell Order Executed: {...}

balances after selling BNB:
[2024-10-08 02:17:05] Printing balances for BNB and USDT
[2024-10-08 02:17:05] Fetching balance for asset: BNB
[2024-10-08 02:17:05] Balance for BNB: 0.00022982 (Free), 0.00000000 (Locked)
[2024-10-08 02:17:05] Fetching balance for asset: USDT
[2024-10-08 02:17:05] Balance for USDT: 0.01760000 (Free), 0.00000000 (Locked)
[2024-10-08 02:17:05] BNB Balance: 0.00022982
[2024-10-08 02:17:05] USDT Balance: 0.0176
[2024-10-08 02:17:05] Fetching current price for symbol: BNBUSDC
[2024-10-08 02:17:05] Current price for BNBUSDC: 572.6
[2024-10-08 02:17:05] Calculating minimum order quantity for price: 522.6, lot size: 0.001, step size: 0.001, min notional: 10
[2024-10-08 02:17:05] Calculated minimum order quantity: 0.02
按下Enter後, 以522.6的價格, 在交易對BNBUSDC上掛限價買單, 購買0.02顆BNB
[2024-10-08 02:17:14] Placing limit buy order for 0.02 BNB at price 522.6 on symbol BNBUSDC
[2024-10-08 02:17:14] Limit Buy Order Executed: {...}
[2024-10-08 02:17:14] Fetching status for order 426065738 on symbol BNBUSDC
[2024-10-08 02:17:14] Order Status: {...}
Order Status: {...}
[2024-10-08 02:17:14] Fetching open orders for symbol: BNBUSDC
[2024-10-08 02:17:14] Open Orders: [{...}]
Open Orders: [{...}]
按下Enter後取消此限價買單
[2024-10-08 02:17:16] Canceling order 426065738 on symbol BNBUSDC
[2024-10-08 02:17:16] Order 426065738 canceled successfully: {...}
按下Enter後, 將以市價花光所有USDC買入BNBUSDC
[2024-10-08 02:17:22] Fetching symbol info for: BNBUSDC
[2024-10-08 02:17:23] Symbol info - Base Asset: BNB, Quote Asset: USDC
[2024-10-08 02:17:23] Buying all available BNB using USDC
[2024-10-08 02:17:23] Fetching balance for asset: USDC
[2024-10-08 02:17:23] Balance for USDC: 14.88760000 (Free), 0.00000000 (Locked)
[2024-10-08 02:17:23] Fetching symbol info for: BNBUSDC
[2024-10-08 02:17:23] Symbol info - Base Asset: BNB, Quote Asset: USDC
[2024-10-08 02:17:23] Fetching lot size and step size from symbol info.
[2024-10-08 02:17:23] Lot Size: 0.001, Step Size: 0.001
[2024-10-08 02:17:23] Fetching current price for symbol: BNBUSDC
[2024-10-08 02:17:23] Current price for BNBUSDC: 572.7
[2024-10-08 02:17:23] Rounded quantity: 0.025 (Original: 0.025995460101274664, Step Size: 0.001)
[2024-10-08 02:17:23] Placing market buy order for 0.025 BNB on symbol BNBUSDC
[2024-10-08 02:17:23] Market Buy Order Executed: {...}

balances after buying BNB:
[2024-10-08 02:17:23] Printing balances for BNB and USDT
[2024-10-08 02:17:23] Fetching balance for asset: BNB
[2024-10-08 02:17:23] Balance for BNB: 0.02521201 (Free), 0.00000000 (Locked)
[2024-10-08 02:17:23] Fetching balance for asset: USDT
[2024-10-08 02:17:23] Balance for USDT: 0.01760000 (Free), 0.00000000 (Locked)
[2024-10-08 02:17:23] BNB Balance: 0.02521201
[2024-10-08 02:17:23] USDT Balance: 0.0176

由於接下來接近尾聲,為了勉強可以完成這三十天的目標,不管MacroHFT的訓練結果如何,我還是會先使用FinRL的API來完成一個自動交易程式,依據DRL策略給出的訊號做ETHUSDT的自動交易。


上一篇
Day 23 - 幣安自動化程式:確認餘額、現貨掛賣
下一篇
Day 25 - 嘗試使用`FinRL`的`BitcoinEnv`,但失敗
系列文
自動交易程式探索30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言