CCXT - 在Python中设置杠杆

0 投票
1 回答
43 浏览
提问于 2025-04-14 16:59

我在用CCXT和Python进行期货交易时,似乎遇到了一些麻烦,特别是在传递值的时候。

现在我有一段代码可以用来开仓、设置止损(SL)和止盈(TP),代码如下:

def open_trade(symbol, entry, leverage, take_profit, stop_loss, position_type, size):
    # Load the time difference
    exchange.load_time_difference()
    
    # Assuming you already have 'exchange' defined somewhere
    ticker = exchange.fetch_ticker(symbol)
    current_price = ticker['last']

    if position_type == 'LONG' and not (entry[1] < current_price < entry[0]):
        print(f"Current price ({current_price}) is not between entry1 ({entry[1]}) and entry2 ({entry[0]}). Signal NOT executed")
        return None
    elif position_type == 'SHORT' and not (entry[0] < current_price < entry[1]):
        print(f"Current price ({current_price}) is not between entry1 ({entry[0]}) and entry2 ({entry[1]}). Signal NOT executed")
        return None

    # Define additional parameters, including leverage
    additional_params = {
        'leverage': calc_leverage(symbol, leverage),
    }

    # Set leverage
    exchange.fapiPrivate_post_leverage({
    "symbol": symbol,
    "leverage": leverage,
})

    # Determine the position side based on the order type
    if position_type == 'LONG':
        additional_params['positionSide'] = 'LONG'
    elif position_type == 'SHORT':
        additional_params['positionSide'] = 'SHORT'
    else:
        print(f"Invalid position_type: {position_type}")
        return None

    # Place market order with additional parameters
    order = exchange.create_order(
        symbol=symbol,
        type='market',
        side='buy' if position_type == 'LONG' else 'sell',
        amount=size,
        params=additional_params,
    )
    position_info = order
    print("Futures position information:")
    print(str(position_info) + "\n")

    # Add stopPrice to additional_params
    additional_params['stopPrice'] = stop_loss
    

    # Place stop loss order
    stop_loss_order = exchange.create_order(
        symbol=symbol,
        type='STOP_MARKET',
        side='sell' if position_type == 'LONG' else 'buy',
        amount=size,
        price=stop_loss,  # This is the stop loss price
        params=additional_params,
    )

    position_info = stop_loss_order
    print("Stop Loss information:")
    print(str(position_info) + "\n")

    size = size/5  # Split the size into 5 take profit orders
    i = 1
    for tp in take_profit:
        # Add stopPrice to additional_params
        additional_params['stopPrice'] = tp
        # Place take profit order
        take_profit_order = exchange.create_order(
            symbol=symbol,
            type='TAKE_PROFIT_MARKET',
            side='sell' if position_type == 'LONG' else 'buy',
            amount=size,
            price=tp,  # This is the take profit price
            params=additional_params,
        )

        position_info = take_profit_order
        print('Take Profit: ' + str(i) + ' information:')
        print(str(position_info) + "\n")
        i += 1

最开始我以为这段代码可以正常工作:

# Define additional parameters, including leverage
    additional_params = {
        'leverage': calc_leverage(symbol, leverage),
    }

但是在测试了不同的信号后,我发现它根本没有起作用……于是我去找了一篇帖子:Binance在Python中使用CCXT时没有考虑杠杆

但即使是那里的代码似乎也没有解决问题:

markets = exchange.load_markets()
market = exchange.market(symbol)  

exchange.fapiPrivate_post_leverage({  
    'symbol': 'symbol',
    'leverage': leverage,
})

而且无论我尝试 BTCUSDTBTC/USDT 还是 BTC/USDT:USDT,都一直返回关于符号的错误,当我使用

ccxt.binanceusdm

或者

AttributeError: 'binance' object has no attribute 'fapiPrivate_post_leverage'

当我使用

ccxt.binance

我是在看到其他帖子后发现这个问题的,帖子建议使用

exchange = ccxt.binanceusdm({
    'apiKey': 'blabla',
    'secret': 'secret',
    'enableRateLimit': True,
    'options': {
        'defaultType': 'future'
    }
})

而不是

exchange = ccxt.binance({...

这个问题不仅限于杠杆,直接在交易中设置止损或止盈也有问题,因此我的代码中有3次重复的

order

任何帮助都将非常感激

1 个回答

0

在文档中有

binance.setLeverage (leverage, symbol[, params])

我不小心错过了这一点,现在代码按预期工作了

撰写回答