首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >尝试修改脚本ccxt python二进制点dca bot

尝试修改脚本ccxt python二进制点dca bot
EN

Stack Overflow用户
提问于 2022-02-09 22:55:37
回答 1查看 547关注 0票数 0

你好,我需要在二进制环境下修改dca bot的python脚本,我想修改在二进制上交易的原始脚本,我修改了exchange部分,但是当我尝试在visual studio中运行该脚本时,遇到了这个问题:

回溯(最近一次调用):文件"c:\Users\TEHH\Desktop\Binance-Futures-DCA-4Bot-main\Binance-Futures-DCA-Bot-main\strategy copy 2.py",第41行,位置=balance‘’info‘

你能帮我修改一下代码以便能在现场使用吗,

github ccxt:https://github.com/ccxt/ccxt.git

代码:

代码语言:javascript
运行
复制
import config
import pandas as pd
import ccxt
import winsound
duration = 1000  # milliseconds
freq = 440  # Hz

# SETTİNGS
symbolName = input("Symbol (BTC, ETH, LTC...): ").upper()
baseOrderSize = float(input("Base Order Size: "))
safetyOrderSize = float(input("Safety Order Size: "))
maxSafetyTradesCount = float(input("Max Safety Trades Count: "))
priceDeviation = float(input("Price Deviation %: "))
safetyOrderStepScale = float(input("Safety Order Step Scale: "))
safetyOrderVolumeScale = float(input("Safety Order Volume Scale: "))
takeProfit = float(input("Take Profit %: "))
stopLoss = float(input("Stop Loss %: "))
positionSide = float(input("Position Side = Only Long(1) - Only Short(2) - Long and Short(3): "))

#ATTRIBUTES
first = True
tradeCount = 1
symbol = symbolName+"/BTC"
mainSafetyOrderSize = safetyOrderSize
mainPriceDeviation = priceDeviation

# API CONNECT
exchange = ccxt.binance({
"apiKey": config.apiKey,
"secret": config.secretKey,
'enableRateLimit': True
})

while True:
    try:
        
        balance = exchange.fetch_balance()
        free_balance = exchange.fetch_free_balance()
        positions = balance['info']['positions']
        newSymbol = symbolName+"BTC"
        current_positions = [position for position in positions if float(position['positionAmt']) != 0 and position['symbol'] == newSymbol]
        position_info = pd.DataFrame(current_positions, columns=["symbol", "entryPrice", "unrealizedProfit", "isolatedWallet", "positionAmt", "positionSide"])
        
        # in position?
        if not position_info.empty and position_info["positionAmt"][len(position_info.index) - 1] != 0:
            inPosition = True
        else: 
            inPosition = False
            longPosition = False
            shortPosition = False
            
        # in long position?
        if not position_info.empty and float(position_info["positionAmt"][len(position_info.index) - 1]) > 0:
            longPosition = True
            shortPosition = False
        # in short position?
        if not position_info.empty and float(position_info["positionAmt"][len(position_info.index) - 1]) < 0:
            shortPosition = True
            longPosition = False
        
        
        # LOAD BARS
        bars = exchange.fetch_ohlcv(symbol, timeframe="1m", since = None, limit = 1)
        df = pd.DataFrame(bars, columns=["timestamp", "open", "high", "low", "close", "volume"])
        
        # Starting price
        if first:
            firstPrice = float(df["close"][len(df.index) - 1])
            first = False

        currentPrice = float(df["close"][len(df.index) - 1])
        
        # LONG ENTER
        def longEnter(alinacak_miktar):
            order = exchange.create_market_buy_order(symbol, alinacak_miktar)
            winsound.Beep(freq, duration)
            
        # LONG EXIT
        def longExit():
            order = exchange.create_market_sell_order(symbol, float(position_info["positionAmt"][len(position_info.index) - 1]), {"reduceOnly": True})
            winsound.Beep(freq, duration)

        # SHORT ENTER
        def shortEnter(alincak_miktar):
            order = exchange.create_market_sell_order(symbol, alincak_miktar)
            winsound.Beep(freq, duration)
            
        # SHORT EXIT
        def shortExit():
            order = exchange.create_market_buy_order(symbol, (float(position_info["positionAmt"][len(position_info.index) - 1]) * -1), {"reduceOnly": True})
            winsound.Beep(freq, duration)

        if inPosition == False:
            priceDeviation = mainPriceDeviation
            safetyOrderSize = mainSafetyOrderSize
        
        # LONG ENTER
        if firstPrice - (firstPrice/100) * priceDeviation >= currentPrice and shortPosition == False and maxSafetyTradesCount>tradeCount and float(free_balance["BTC"]) >= baseOrderSize and (positionSide == 1 or positionSide == 3):
            if tradeCount == 0:
                alinacak_miktar = (baseOrderSize * 1 ) / float(df["close"][len(df.index) - 1])
            if tradeCount > 0:
                alinacak_miktar = (safetyOrderSize * 1 ) / float(df["close"][len(df.index) - 1])
                safetyOrderSize = safetyOrderSize*safetyOrderVolumeScale

            priceDeviation = priceDeviation * safetyOrderStepScale
            longEnter(alinacak_miktar)
            print("LONG ENTER")
            first = True
            tradeCount = tradeCount + 1
        
        # SHORT ENTER
        if ((firstPrice / 100) * priceDeviation) + firstPrice <= currentPrice and longPosition == False and maxSafetyTradesCount>tradeCount and float(free_balance["BTC"]) >= baseOrderSize and (positionSide == 2 or positionSide == 3): 
            if tradeCount == 0:
                alinacak_miktar = (baseOrderSize * 1 ) / float(df["close"][len(df.index) - 1])
            if tradeCount > 0:
                alinacak_miktar = (safetyOrderSize * 1 ) / float(df["close"][len(df.index) - 1])
                safetyOrderSize = safetyOrderSize*safetyOrderVolumeScale

            priceDeviation = priceDeviation * safetyOrderStepScale
            shortEnter(alinacak_miktar)
            print("SHORT ENTER")
            first = True
            tradeCount = tradeCount + 1
            
            
        # LONG TAKE PROFIT
        if longPosition and ((float(position_info["entryPrice"][len(position_info.index) - 1])/100)*takeProfit)+float(position_info["entryPrice"][len(position_info.index) - 1]) < currentPrice and (positionSide == 1 or positionSide == 3):
            print("TAKE PROFIT")
            longExit()
            first = True
            tradeCount = 0
            
        # SHORT TAKE PROFIT
        if shortPosition and float(position_info["entryPrice"][len(position_info.index) - 1]) - (float(position_info["entryPrice"][len(position_info.index) - 1])/100) * takeProfit >= currentPrice and (positionSide == 2 or positionSide == 3):
            print("TAKE PROFIT")
            shortExit()
            first = True
            tradeCount = 0
            
        # LONG STOP LOSS
        if longPosition and (float(free_balance["BTC"]) <= baseOrderSize or maxSafetyTradesCount<=tradeCount) and firstPrice - (firstPrice/100) * stopLoss >= currentPrice and (positionSide == 1 or positionSide == 3):
            print("STOP LOSS")
            longExit()
            first = True
            tradeCount = 0
        
        # SHORT STOP LOSS
        if shortPosition and (float(free_balance["BTC"]) <= baseOrderSize or maxSafetyTradesCount<=tradeCount) and ((firstPrice / 100) * stopLoss) + firstPrice <= currentPrice and (positionSide == 2 or positionSide == 3):
            print("STOP LOSS")
            shortExit()
            first = True
            tradeCount = 0
            
            
        if longPosition:
            print("In Long Position")
        if shortPosition:
            print("In Short Position")
        if inPosition:
            print("Trade Count: ", tradeCount, " Avarege Price: ", float(position_info["entryPrice"][len(position_info.index) - 1]), " Free btc ", round(float(free_balance["BTC"]),2), " Total Money: ", round(float(balance['total']["BTC"]),2))
        if inPosition == False: 
            print("Starting Price: ", firstPrice, " Current Price: ", currentPrice, " Total Money: ", round(float(balance['total']["BTC"]),2))
        print("=======================================================================================================================================")

    except ccxt.BaseError as Error:
        print ("[ERROR] ", Error )
        continue
EN

回答 1

Stack Overflow用户

发布于 2022-02-16 17:20:02

上面的图片是运行适用于(由ccxt库包装)的方法.fetch_balance()的结果。它是JSON格式的,我相信它不是

代码语言:javascript
运行
复制
positions = balance['info']['positions']

你应该试试

代码语言:javascript
运行
复制
positions = balance['info']['balances']

我不能保证,如果这将通过,其余的代码将工作,因为期货是不同的地方,我不熟悉期货。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71057841

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档