当前位置: 首页>>代码示例>>Python>>正文


Python ccxt.binance方法代码示例

本文整理汇总了Python中ccxt.binance方法的典型用法代码示例。如果您正苦于以下问题:Python ccxt.binance方法的具体用法?Python ccxt.binance怎么用?Python ccxt.binance使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ccxt的用法示例。


在下文中一共展示了ccxt.binance方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _get_tools

# 需要导入模块: import ccxt [as 别名]
# 或者: from ccxt import binance [as 别名]
def _get_tools():
    config = load_test_config()
    symbol = "BTC/USDT"
    exchange_manager = ExchangeManager(config, ccxt.binance, is_simulated=True)
    await exchange_manager.initialize()
    exchange_inst = exchange_manager.get_exchange()
    trader_inst = TraderSimulator(config, exchange_inst, 0.3)
    await trader_inst.portfolio.initialize()
    trader_inst.stop_order_manager()
    trader_inst.portfolio.portfolio["SUB"] = {
        Portfolio.TOTAL: 0.000000000000000000005,
        Portfolio.AVAILABLE: 0.000000000000000000005
    }
    trader_inst.portfolio.portfolio["BNB"] = {
        Portfolio.TOTAL: 0.000000000000000000005,
        Portfolio.AVAILABLE: 0.000000000000000000005
    }
    trader_inst.portfolio.portfolio["USDT"] = {
        Portfolio.TOTAL: 2000,
        Portfolio.AVAILABLE: 2000
    }

    trading_mode = MarketMakerTradingMode(config, exchange_inst)

    return config, exchange_inst, trader_inst, symbol, trading_mode 
开发者ID:Drakkar-Software,项目名称:OctoBot-Tentacles,代码行数:27,代码来源:test_market_marker_trading_mode.py

示例2: __init__

# 需要导入模块: import ccxt [as 别名]
# 或者: from ccxt import binance [as 别名]
def __init__(self, api_key, api_secret):
        self.ccxtClient = ccxt.binance({
            'apiKey': api_key,
            'secret': api_secret,
        }) 
开发者ID:szferguson,项目名称:Binance-Trailing-Stop-Loss,代码行数:7,代码来源:binance.py

示例3: create_order

# 需要导入模块: import ccxt [as 别名]
# 或者: from ccxt import binance [as 别名]
def create_order(exchange, symbol, price, amount, order_type, side):

    try:
        if exchange == 'binance':  # 币安的

            price = float(price)
            amount = float(amount)
            print(f"symbol={symbol}, type={order_type}, price={price} amount={amount}, side={side}")

            order = binance.create_order(symbol=symbol, type=order_type, price=price, amount=amount, side=side)
            # ccxt.huobipro().create_order()
            print(order)
            bitquant.send(order)

        elif exchange == 'huobi':  # 火币的.
            pass  # 自己去实现下.

        else:
            pass

    except Exception as error:
        print(error)
        bitquant.send(error) 
开发者ID:ramoslin02,项目名称:51bitqunt,代码行数:25,代码来源:wechat_orderbot.py

示例4: _get_tools

# 需要导入模块: import ccxt [as 别名]
# 或者: from ccxt import binance [as 别名]
def _get_tools():
    symbol = "BTC/USD"
    exchange_traders = {}
    exchange_traders2 = {}
    config = load_test_config()
    config[CONFIG_EVALUATOR]["FullMixedStrategiesEvaluator"] = False
    config[CONFIG_EVALUATOR]["StaggeredStrategiesEvaluator"] = True
    config[CONFIG_TRADING_TENTACLES]["DailyTradingMode"] = False
    config[CONFIG_TRADING_TENTACLES]["StaggeredOrdersTradingMode"] = True
    AdvancedManager.create_class_list(config)
    exchange_manager = ExchangeManager(config, ccxt.binance, is_simulated=True)
    await exchange_manager.initialize()
    exchange_inst = exchange_manager.get_exchange()
    trader_inst = TraderSimulator(config, exchange_inst, 0.3)
    await trader_inst.initialize()
    trader_inst.stop_order_manager()
    exchange_traders[exchange_inst.get_name()] = trader_inst

    trading_mode = StaggeredOrdersTradingMode(config, exchange_inst)
    trading_mode.trading_config = _get_multi_symbol_staggered_config()
    trader_inst.register_trading_mode(trading_mode)

    final_evaluator, staggered_strategy_evaluator = _add_symbol("Bitcoin", symbol, config, exchange_traders,
                                                                exchange_traders2, exchange_inst, trading_mode)

    trader_inst.portfolio.portfolio["USD"] = {
        Portfolio.TOTAL: 1000,
        Portfolio.AVAILABLE: 1000
    }
    trader_inst.portfolio.portfolio["BTC"] = {
        Portfolio.TOTAL: 10,
        Portfolio.AVAILABLE: 10
    }
    final_evaluator.lowest_buy = 1
    final_evaluator.highest_sell = 10000
    final_evaluator.operational_depth = 50
    final_evaluator.spread = 0.06
    final_evaluator.increment = 0.04

    return final_evaluator, trader_inst, staggered_strategy_evaluator 
开发者ID:Drakkar-Software,项目名称:OctoBot-Tentacles,代码行数:42,代码来源:test_staggered_orders_trading_mode.py

示例5: scalping_orders

# 需要导入模块: import ccxt [as 别名]
# 或者: from ccxt import binance [as 别名]
def scalping_orders(exchange = ccxt.binance(), coin='BTC/USDT', wait=1, tot_time=1):
    #Function for placing 'scalp orders'
    #Calls on Visualizing Scalping Orders Function
    ap, aq, bp, bq, place_ask_order, place_bid_order, spread, proj_spread, max_bid, min_ask = visualize_market_depth(wait, tot_time, coin, 5, exchange)
    print("Coin: {}\nPrice to Place Ask Order: {}\nPrice to place Bid Order: {}".format(coin, place_ask_order, place_bid_order))
    print("Spread: {} % Projected Spread {} %".format(spread, proj_spread))
    print("Max Bid: {} Min Ask: {}".format(max_bid, min_ask))
    #Place Orders based on calculated bid-ask orders if projected > 0.05% (transaction fee)
    #Documentation: http://python-binance.readthedocs.io/en/latest/account.html#orders
    """
    if proj_spread > 0.05:
        quant1=100          #Determine Code Required to calculate 'minimum' quantity
        #Place Bid Order:
        bid_order1 = client.order_limit_buy(
            symbol=coin,
            quantity=quant1,
            price=place_bid_order)
        #Place Ask Order
        ask_order1 = client.order_limit_sell(
            symbol=coin,
            quantity=quant1,
            price=place_ask_order)


    #Place second order if current spread > 0.05% (transaction fee)

    """ 
开发者ID:Roibal,项目名称:Cryptocurrency-Trading-Bots-Python-Beginner-Advance,代码行数:29,代码来源:Advanced_Cryptocurrency_Trading_Bot.py

示例6: _get_tools

# 需要导入模块: import ccxt [as 别名]
# 或者: from ccxt import binance [as 别名]
def _get_tools():
    symbol = "BTC/USDT"
    exchange_traders = {}
    exchange_traders2 = {}
    config = load_test_config()
    AdvancedManager.create_class_list(config)
    exchange_manager = ExchangeManager(config, ccxt.binance, is_simulated=True)
    await exchange_manager.initialize()
    exchange_inst = exchange_manager.get_exchange()
    trader = TraderSimulator(config, exchange_inst, 0.3)
    await trader.initialize()
    trader.stop_order_manager()
    trader_inst2 = TraderSimulator(config, exchange_inst, 0.3)
    await trader_inst2.initialize()
    trader_inst2.stop_order_manager()
    crypto_currency_evaluator = CryptocurrencyEvaluator(config, "Bitcoin", [])
    symbol_evaluator = SymbolEvaluator(config, symbol, crypto_currency_evaluator)
    exchange_traders[exchange_inst.get_name()] = trader
    exchange_traders2[exchange_inst.get_name()] = trader_inst2
    symbol_evaluator.set_trader_simulators(exchange_traders)
    symbol_evaluator.set_traders(exchange_traders2)
    symbol_evaluator.strategies_eval_lists[exchange_inst.get_name()] = \
        EvaluatorCreator.create_strategies_eval_list(config)

    trading_mode = DipAnalyserTradingMode(config, exchange_inst)
    trader.register_trading_mode(trading_mode)
    trading_mode.add_symbol_evaluator(symbol_evaluator)
    decider = trading_mode.get_only_decider_key(symbol)
    creator_key = trading_mode.get_only_creator_key(symbol)
    creator = trading_mode.get_creator(symbol, creator_key)

    dip_strategy_evaluator = symbol_evaluator.strategies_eval_lists[exchange_inst.get_name()][0]

    trader.portfolio.portfolio["USDT"] = {
        Portfolio.TOTAL: 2000,
        Portfolio.AVAILABLE: 2000
    }
    return decider, creator, dip_strategy_evaluator, trader 
开发者ID:Drakkar-Software,项目名称:OctoBot-Tentacles,代码行数:40,代码来源:test_dip_analyser_trading_mode.py

示例7: _get_tools

# 需要导入模块: import ccxt [as 别名]
# 或者: from ccxt import binance [as 别名]
def _get_tools():
    symbol = "BTC/USDT"
    exchange_traders = {}
    exchange_traders2 = {}
    config = load_test_config()
    AdvancedManager.create_class_list(config)
    exchange_manager = ExchangeManager(config, ccxt.binance, is_simulated=True)
    await exchange_manager.initialize()
    exchange_inst = exchange_manager.get_exchange()
    trader_inst = TraderSimulator(config, exchange_inst, 0.3)
    await trader_inst.initialize()
    trader_inst.stop_order_manager()
    trader_inst2 = TraderSimulator(config, exchange_inst, 0.3)
    await trader_inst2.initialize()
    trader_inst2.stop_order_manager()
    crypto_currency_evaluator = CryptocurrencyEvaluator(config, "Bitcoin", [])
    symbol_evaluator = SymbolEvaluator(config, symbol, crypto_currency_evaluator)
    exchange_traders[exchange_inst.get_name()] = trader_inst
    exchange_traders2[exchange_inst.get_name()] = trader_inst2
    symbol_evaluator.set_trader_simulators(exchange_traders)
    symbol_evaluator.set_traders(exchange_traders2)
    symbol_evaluator.strategies_eval_lists[exchange_inst.get_name()] = \
        EvaluatorCreator.create_strategies_eval_list(config)

    trading_mode = DailyTradingMode(config, exchange_inst)
    trading_mode.add_symbol_evaluator(symbol_evaluator)
    final_evaluator = trading_mode.get_only_decider_key(symbol)

    trader_inst.portfolio.portfolio["USDT"] = {
        Portfolio.TOTAL: 2000,
        Portfolio.AVAILABLE: 2000
    }
    return final_evaluator, trader_inst 
开发者ID:Drakkar-Software,项目名称:OctoBot-Tentacles,代码行数:35,代码来源:test_daily_trading_mode_decider.py

示例8: receive_message

# 需要导入模块: import ccxt [as 别名]
# 或者: from ccxt import binance [as 别名]
def receive_message(msg: Message):
    txt = msg.text
    # txt的格式 #ex=binance, price=300.8, 'amount'=1, symbol=BTC/USDT, type=limit#
    # #symbol, price, amount, type, side# 看你对对订单的数据定义.
    print(txt)

    try:
        txt = txt.strip(' ')

        if txt.find("下单") >= 0:
            bitquant.send("#交易所名称如binance/huobipro/okex等,交易对如BTC/USDT,下单价格,下单数量,订单类型如limit/market,买或卖如buy/sell#"
                          )

        if txt.startswith('#') and txt.endswith("#"):
            txt = txt.strip('#')  # 去掉头尾的两个#字符.
            order_fields = txt.split(',')  # 分割键值对.  #binance, BTC/USDT, 10000, 0.01, limit, buy#
            order_datas = []

            for item in order_fields:
                order_datas.append(item.strip(" "))
                # 把空白字符给处理掉, 如下面的输入.
                #binance,  BTC/USDT, 9000, 0.01, limit, buy#

            print(order_datas)
            if len(order_datas) >= 6:
                create_order(order_datas[0], order_datas[1], order_datas[2], order_datas[3], order_datas[4], order_datas[5])
    except Exception as error:
        bitquant.send(error)


    # 还可处理撤单、以及各种逻辑.
    #binance, cancel_id#    #binance,xxxxxxx#

    #binance, 查询账户# 
开发者ID:ramoslin02,项目名称:51bitqunt,代码行数:36,代码来源:wechat_orderbot.py

示例9: __init__

# 需要导入模块: import ccxt [as 别名]
# 或者: from ccxt import binance [as 别名]
def __init__(self, ccxt_config={}):
        if self.FUTURE:
            ccxt_config.setdefault('options', {})['defaultType'] = 'future'
        ApiBase.__init__(self)
        ccxt.binance.__init__(self, ccxt_config)
        self.load_markets()

        # silence linter
        self.fapiPrivate_get_positionrisk = getattr(
            self, 'fapiPrivate_get_positionrisk') 
开发者ID:penta2019,项目名称:btc_bot_framework,代码行数:12,代码来源:api.py

示例10: __init__

# 需要导入模块: import ccxt [as 别名]
# 或者: from ccxt import binance [as 别名]
def __init__(self, name):
        self.name = name
        self.conf = Settings.makeSettings(Settings.loadTomlSettings(name))
        secret = open(self.conf.credentialsFilePath).read()
        secret = secret.split('\n')
        self.API = ccxt.binance({
            'apiKey': secret[0],
            'secret': secret[1]
        })
        self.API.load_markets() 
开发者ID:Gab0,项目名称:japonicus,代码行数:12,代码来源:exchangeMonitor.py

示例11: visualize_market_depth

# 需要导入模块: import ccxt [as 别名]
# 或者: from ccxt import binance [as 别名]
def visualize_market_depth(wait_time_sec='1', tot_time='1', sym='BTC/USDT', precision=5, exchange=ccxt.binance()):
    cycles = int(tot_time)/int(wait_time_sec)
    start_time = time.asctime()         #Trans CCXT
    fig, ax = plt.subplots()
    for i in range(1,int(cycles)+1):
        ask_pri, ask_quan, bid_pri, bid_quan, ask_order, bid_order = market_depth(sym, exchange)

        #print(ask_price)
        plt.plot(ask_pri, ask_quan, color = 'red', label='asks-cycle: {}'.format(i))
        plt.plot(bid_pri, bid_quan, color = 'blue', label = 'bids-cycle: {}'.format(i))

        #ax.plot(depth['bids'][0], depth['bids'][1])
        max_bid = max(bid_pri)
        min_ask = min(ask_pri)
        max_quant = max(ask_quan[-1], bid_quan[-1])
        spread = round(((min_ask-max_bid)/min_ask)*100,5)   #Spread based on market
        proj_order_spread = round(((ask_order-bid_order)/ask_order)*100, precision)
        price=round(((max_bid+min_ask)/2), precision)
        plt.plot([price, price],[0, max_quant], color = 'green', label = 'Price - Cycle: {}'.format(i)) #Vertical Line for Price
        plt.plot([ask_order, ask_order],[0, max_quant], color = 'black', label = 'Ask - Cycle: {}'.format(i))
        plt.plot([bid_order, bid_order],[0, max_quant], color = 'black', label = 'Buy - Cycle: {}'.format(i))
        #plt.plot([min_ask, min_ask],[0, max_quant], color = 'grey', label = 'Min Ask - Cycle: {}'.format(i))
        #plt.plot([max_bid, max_bid],[0, max_quant], color = 'grey', label = 'Max Buy - Cycle: {}'.format(i))
        ax.annotate("Max Bid: {} \nMin Ask: {}\nSpread: {} %\nCycle: {}\nPrice: {}"
                    "\nPlace Bid: {} \nPlace Ask: {}\n Projected Spread: {} %".format(max_bid, min_ask, spread, i, price, bid_order, ask_order, proj_order_spread),
                    xy=(max_bid, ask_quan[-1]), xytext=(max_bid, ask_quan[0]))
        if i==(cycles+1):
            break
        else:
            time.sleep(int(wait_time_sec))
    #end_time = time.asctime()
    ax.set(xlabel='Price', ylabel='Quantity',
       title='{} Order Book: {} \n {}\n Cycle Time: {} seconds - Num Cycles: {}'.format(exchange.id, sym, start_time, wait_time_sec, cycles))
    plt.legend()
    plt.show()
    return ask_pri, ask_quan, bid_pri, bid_quan, ask_order, bid_order, spread, proj_order_spread, max_bid, min_ask 
开发者ID:Roibal,项目名称:Cryptocurrency-Trading-Bots-Python-Beginner-Advance,代码行数:38,代码来源:Advanced_Cryptocurrency_Trading_Bot.py

示例12: _get_tools

# 需要导入模块: import ccxt [as 别名]
# 或者: from ccxt import binance [as 别名]
def _get_tools(event_loop):
    config = load_test_config()
    symbol = "BTC/USDT"
    exchange_traders = {}
    exchange_traders2 = {}
    time_frame = TimeFrames.FIVE_MINUTES
    AdvancedManager.create_class_list(config)
    exchange_manager = ExchangeManager(config, ccxt.binance, is_simulated=True)
    await exchange_manager.initialize()
    exchange_inst = exchange_manager.get_exchange()
    symbol_time_frame_updater_thread = GlobalPriceUpdater(exchange_inst)
    trader_inst = TraderSimulator(config, exchange_inst, 0.3)
    await trader_inst.initialize()
    trader_inst.stop_order_manager()
    trader_inst2 = TraderSimulator(config, exchange_inst, 0.3)
    await trader_inst2.initialize()
    trader_inst2.stop_order_manager()
    trader_inst2.set_enabled(False)
    trader_inst.portfolio.portfolio["SUB"] = {
        Portfolio.TOTAL: 0.000000000000000000005,
        Portfolio.AVAILABLE: 0.000000000000000000005
    }
    trader_inst.portfolio.portfolio["BNB"] = {
        Portfolio.TOTAL: 0.000000000000000000005,
        Portfolio.AVAILABLE: 0.000000000000000000005
    }
    trader_inst.portfolio.portfolio["USDT"] = {
        Portfolio.TOTAL: 2000,
        Portfolio.AVAILABLE: 2000
    }
    crypto_currency_evaluator = CryptocurrencyEvaluator(config, "Bitcoin", [])
    symbol_evaluator = SymbolEvaluator(config, symbol, crypto_currency_evaluator)

    exchange_traders[exchange_inst.get_name()] = trader_inst
    exchange_traders2[exchange_inst.get_name()] = trader_inst2
    symbol_evaluator.set_trader_simulators(exchange_traders)
    symbol_evaluator.set_traders(exchange_traders2)
    trading_mode_inst = get_activated_trading_mode(config)(config, exchange_inst)
    _ = EvaluatorTaskManager(config, time_frame, symbol_time_frame_updater_thread,
                             symbol_evaluator, exchange_inst, trading_mode_inst, [], event_loop)
    trading_mode = HighFrequencyMode(config, exchange_inst)
    trading_mode.add_symbol_evaluator(symbol_evaluator)
    decider = trading_mode.get_only_decider_key(symbol)
    await decider.initialize()

    return config, exchange_inst, trader_inst, symbol, trading_mode 
开发者ID:Drakkar-Software,项目名称:OctoBot-Tentacles,代码行数:48,代码来源:test_high_frequency_trading_mode.py

示例13: crawl_bybit_datas

# 需要导入模块: import ccxt [as 别名]
# 或者: from ccxt import binance [as 别名]
def crawl_bybit_datas(symbol, start_time, end_time):
    """
    爬取交易所数据的方法.
    :param symbol: 请求的symbol: like BTC/USDT, ETH/USD等。
    :param start_time: like 2018-1-1
    :param end_time: like 2019-1-1
    :return:
    """
    print(ccxt.__version__)  # 1.18.1213  1.26.50
    # pip install ccxt==1.26.50 通过这个命令来安装最新的版本.
    # exchange_class = getattr(ccxt, 'bybit')  # 获取交易所的名称 ccxt.binance
    # exchange = exchange_class()  # 交易所的类. 类似 ccxt.bitfinex()
    exchange = ccxt.bybit()

    print(exchange)
    # exit()

    current_path = os.getcwd()
    file_dir = os.path.join(current_path, symbol.replace('/', ''))
    print(file_dir)
    if not os.path.exists(file_dir):
        # 如果这个文件路径不存在,则创建这个文件夹,来存放数据.
        os.makedirs(file_dir)

    start_time = datetime.datetime.strptime(start_time, '%Y-%m-%d')
    end_time = datetime.datetime.strptime(end_time, '%Y-%m-%d')

    start_time_stamp = int(time.mktime(start_time.timetuple())) * 1000
    end_time_stamp = int(time.mktime(end_time.timetuple())) * 1000

    limit_count = 200  # bybit 请求的数据有限制,每次只能请求200个.

    while True:
        try:
            print(start_time_stamp)
            data = exchange.fetch_ohlcv(symbol, timeframe='1m', since=start_time_stamp, limit=limit_count)
            df = pd.DataFrame(data)
            df.rename(columns={0: 'open_time', 1: 'open', 2: 'high', 3: 'low', 4: 'close', 5: 'volume'}, inplace=True)

            start_time_stamp = int(df.iloc[-1]['open_time'])  # 获取下一个次请求的时间.
            filename = str(start_time_stamp) + '.csv'
            save_file_path = os.path.join(file_dir, filename)
            print("文件保存路径为:%s" % save_file_path)
            df.set_index('open_time', drop=True, inplace=True)
            df.to_csv(save_file_path)

            if start_time_stamp > end_time_stamp:
                print("完成数据的请求.")
                break

            time.sleep(0.2)  # 1/25

        except Exception as error:
            print(error)
            time.sleep(10) 
开发者ID:ramoslin02,项目名称:51bitqunt,代码行数:57,代码来源:crawl_kline_data.py

示例14: market_depth

# 需要导入模块: import ccxt [as 别名]
# 或者: from ccxt import binance [as 别名]
def market_depth(sym, exchange=ccxt.binance(), num_entries=20):
    #Get market depth
    #Retrieve and format market depth (order book) including time-stamp
    i=0     #Used as a counter for number of entries
    print("Order Book: ") #convert_time_binance(client.get_server_time()))   #Transfer to CCXT
    exchange.verbose = True
    depth = exchange.fetch_order_book(symbol=sym)               #Transf'd to CCXT
    #pprint(depth)
    print(depth['asks'][0])
    ask_tot=0.0
    ask_price =[]
    ask_quantity = []
    bid_price = []
    bid_quantity = []
    bid_tot = 0.0
    place_order_ask_price = 0
    place_order_bid_price = 0
    max_order_ask = 0
    max_order_bid = 0
    print("\n", sym, "\nDepth     ASKS:\n")         #Edit to work with CCXT
    print("Price     Amount")
    for ask in depth['asks']:
        if i<num_entries:
            if float(ask[1])>float(max_order_ask):
                #Determine Price to place ask order based on highest volume
                max_order_ask=ask[1]
                #print("Max Order ASK: ", max_order_ask)
                place_order_ask_price=round(float(ask[0]),5)-0.0001
            #ask_list.append([ask[0], ask[1]])
            ask_price.append(float(ask[0]))
            ask_tot+=float(ask[1])
            ask_quantity.append(ask_tot)
            #print(ask)
            i+=1
    j=0     #Secondary Counter for Bids
    print("\n", sym, "\nDepth     BIDS:\n")
    print("Price     Amount")
    for bid in depth['bids']:
        if j<num_entries:
            if float(bid[1])>float(max_order_bid):
                #Determine Price to place ask order based on highest volume
                max_order_bid=bid[1]
                #print("Max Order BID: ", max_order_bid)
                place_order_bid_price=round(float(bid[0]),5)+0.0001
            bid_price.append(float(bid[0]))
            bid_tot += float(bid[1])
            bid_quantity.append(bid_tot)
            #print(bid)
            j+=1
    return ask_price, ask_quantity, bid_price, bid_quantity, place_order_ask_price, place_order_bid_price
    #Plot Data 
开发者ID:Roibal,项目名称:Cryptocurrency-Trading-Bots-Python-Beginner-Advance,代码行数:53,代码来源:Advanced_Cryptocurrency_Trading_Bot.py


注:本文中的ccxt.binance方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。