handler.setLevel(logging.DEBUG) handler.setFormatter(formatter) logger.addHandler(console) logger.addHandler(handler) f = open('accounts.txt') lines = f.readlines() acct_id = int(lines[-1]) api_key = lines[acct_id * 2 - 2].strip('\n') seceret_key = lines[acct_id * 2 - 1].strip('\n') fcoin = Fcoin() fcoin.auth(api_key, seceret_key) # fcoin.margin_buy('ethusdt', 0.01, 10) ex0 = ccxt.fcoin() ex1 = ccxt.okex3() ex2 = ccxt.binance() ex3 = ccxt.huobipro() type = 'limit' trend = 0 trend_0, trend_1, trend_2, trend_3, trend_cmb = [], [], [], [], [] pre_price_0 = 0 pre_price_1, score_1 = 0, 0 pre_price_2, score_2 = 0, 0 pre_price_3, score_3 = 0, 0 pre_price_4, score_4 = 0, 0 pre_price_5, score_5 = 0, 0 pre_price_cmb, score_cmb = 0, 0 buy_id = [] sell_id = [] loop = 0 while True: loop += 1
import ccxt import time from pprint import pprint import os import logging import datetime huobipro = ccxt.huobipro({ 'apiKey': '', 'secret': '', }) balance = huobipro.fetch_balance()['total']['USDT'] print(balance)
'aofex', 'bequant', 'bitkk', 'bitmax', 'gateio', 'hitbtc', 'hollaex', 'huobipro', 'kucoin', 'latoken', 'lbank', 'okex' ] gap_retrieval_interval = 5 gap_recheck_interval = 10 gap_fetch_interval = 25 aofex = ccxt.aofex() bequant = ccxt.bequant() bitkk = ccxt.bitkk() bitmax = ccxt.bitmax() gateio = ccxt.gateio() hitbtc = ccxt.hitbtc() hollaex = ccxt.hollaex() huobipro = ccxt.huobipro() kucoin = ccxt.kucoin() latoken = ccxt.latoken() lbank = ccxt.lbank() okex = ccxt.okex() lbank.apiKey = '26b170f8-d842-49f2-a97d-d2c9d8fbf69e' lbank.secret = 'MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKGUSuql25yd1YQHrwSm9JUglV+ExhaTHVEFx08ekYmxZ1fI0Ly888fEQKlVmuMBlCYWMejA8JKvSL5tndawzPL/2nEjf99TuTeTXJoxnbyKeO5v62vKCg1ZKr39VPsKFJWeJj6r2xv4YhjCRSpfQex4cW8Ptb0evPMluom7bAf5AgMBAAECgYArhJgk2KTsaqoeFD+0Hg9TtuHkRwte+yJzNv42NgJ2tlwiDYkCvFVgIWBU+yRrLXqsQ2AP0x84MpOCDl3re9TG0chAW5vQMZSMd/ecg/KQARQUsMWS9YE97BUeqEgkUUHhW9fx6qxswYWCNzg4FPz77Pi8SOnAiHV88wPKtIUhnQJBAPvKwp+JdzRvx2DqISdDTnKFWj73qWLFkP6jlLZwkGZCks6LW5WDSI2BlbbMFW9+lQ8pJBC50xOlTRl9w79/LGcCQQCkR5Ns07tdvguM3/d5JM/DzSXsff7WiO+MtY+84WuP9lj+jFf2IEHKEttrC1R5HAuwg34CepSomWtcEWmFLGyfAkBuv75fIb226LuPmyu981Lb+F+7dn+gnDmsZxMQM+6vq/SauJ0t5DLTWv4ZCycahVjW9EeSu8llyL1iyviAkFVdAkACYufJVOoL2o7gZQB7SgWamohKfyoMg8C3Eowb+kpNtQ5l5DQC50UNYmi9jVSUzct9rOtPregq6s+cbsRRouuRAkAtlNZ4Ag7uj9n67ClneAQKguDvUeZLBbQF0s2hFIaeYwEqcuo8mLECjWc35xSS8DZwnRzg8pu8Uo/8S10UWhEU' line_token = 'QcmhPgDAY69Sit9fxbJzy8lE5C98bumPzSHcSbe3UyX' def short_entry(xrp_balance, usdt_balance): lbank_ticker = lbank.fetch_ticker('XRP/USDT') lbank_last = lbank_ticker['last'] adjusted_rate_for_limit_sell = lbank_last * 0.01
# API KEYS ZONE BITMEX_API_KEY = '' BITMEX_API_SECRET = '' # SL & TP LEVELS SL_LEVEL = 200 TP_LEVEL = 500 SL2_LEVEL = 100 SL_OFFSET = 60 # TRADE SIZE TRADE_SIZE = 100 exchanges = {'binance': binance(), 'bitstamp': bitstamp(), 'bitfinex': bitfinex(), 'coinbase': coinbasepro(), 'bitmex': bitmex(), 'hitbtc': hitbtc2(), 'kraken': kraken(), 'bittrex': bittrex(), 'huobi': huobipro()} symbols = {'binance': 'BTC/USDC', 'bitstamp': 'BTC/USD', 'bitfinex': 'BTC/USD', 'coinbase': 'BTC/USD', 'bitmex': 'BTC/USD', 'hitbtc': 'BTC/USDT', 'kraken': 'BTC/USD', 'bittrex': 'BTC/USD', 'huobi': 'BTC/USDT'} btmx = bitmex({'apiKey': BITMEX_API_KEY, 'secret': BITMEX_API_SECRET}) new_signal = False hour_closed = False # uncomment for testnet # if 'test' in btmx.urls: # btmx.urls['api'] = btmx.urls['test'] # ←----- switch the base URL to testnet # exchanges['bitmex'].urls['api'] = exchanges['bitmex'].urls['test']
def __init__(self, key, secret): config = {'apiKey': key, 'secret': secret, 'enableRateLimit': True} json_str = json.dumps(config) print(json_str) self.exchange = ccxt.huobipro(config) self.exchange.load_markets()
'exchangeName': "gdax", 'database': gdax_db }) bitfinex = ccxt.bitfinex({ 'rateLimit': 3000, 'enableRateLimit': True, # 'verbose': True, 'exchangeName': "bitfinex", 'database': bitfinex_db }) huobipro = ccxt.huobipro({ 'rateLimit': 3000, 'enableRateLimit': True, # 'verbose': True, 'exchangeName': "huobipro", 'database': huobipro_db }) kraken = ccxt.kraken({ 'rateLimit': 3000, 'enableRateLimit': True, # 'verbose': True, 'exchangeName': "kraken", 'database': kraken_db }) binance = ccxt.binance({ 'rateLimit': 3000, 'enableRateLimit': True,
premiumwinners.append(arb) ftx = ccxt.ftx({'enableRateLimit': True, 'rateLimit': 36}) markets = binance.fetchMarkets() futs = '200925' for m in markets: #print(m['id']) try: binance.dapiPrivatePostLeverage({'symbol': m['id'], 'leverage': 75}) except: abc = 123 huobi = ccxt.huobipro({ "urls": { 'api': { 'public': 'https://api.hbdm.com/swap-api', 'private': 'https://api.hbdm.com/swap-api' } } }) insts = binance.fetchMarkets() #print(insts[0]) bin_futures_all = insts funding = {} exchanges = ['binance', 'kraken', 'ftx', 'huobi', 'okex'] mids = {} for ex in exchanges: funding[ex] = {} mids[ex] = {} expis = {} futureends = ["_CW", "_NW", "_CQ", "_NQ"]
dateArray = datetime.datetime.utcfromtimestamp(ts) otherStyleTime = dateArray.strftime("%H:%M") return otherStyleTime if __name__ == '__main__': ma1 = 5 ma2 = 20 series1 = "ma{}".format(ma1) series2 = "ma{}".format(ma2) # 总资产 Money = 10000 # 查询k线 ex = ccxt.huobipro() kline_1m = ex.fetch_ohlcv("EOS/USDT", "1m", limit=200) # 准备数据,日期升序排列 df = pd.DataFrame(kline_1m, columns=['date', 'open', 'high', 'low', "close", "vol"]) df['date'] = df['date'].apply(toDate) df = df.set_index('date') df = df.sort_values("date") # 计算均线 df[series1] = df["close"].rolling(window=ma1, center=False).mean() # 计算5日均线 df[series2] = df["close"].rolling(window=ma2, center=False).mean() # 计算20日均线
bid1 = 0 ask1 = 0 bid2 = 0 ask2 = 0 #最小交易量 minamount = 0.5 minpercent = 0.003 #货币对 pair = '' pair2 = '' # 线程池 threads = [] # 实例化FCOIN接口 fcoin = Fcoin() fcoin.auth(config.apikey, config.secretkey) huobi = ccxt.huobipro() refresh_flag1 = 0 refresh_flag2 = 0 maxpercent1 = -10 maxpercent2 = -10 filename1 = '' ###################################################################################### # 执行交易策略 def runStrategy(): try: global bid1, ask1, refresh_flag1, bid2, ask2, refresh_flag2, maxpercent1, maxpercent2 if (refresh_flag1 == 0): print("FCOIN行情数据未更新!")
def __init__(self, apikey, secretkey): super().__init__() self.ccxt_exchange = ccxt.huobipro({ 'apiKey': apikey, 'secret': secretkey, })
#!/usr/bin/env python # -*- coding: utf-8 -*- #import flexx import ccxt config={ "apiKey": "", "secret": "" } hb = ccxt.huobipro(config) pair='BTC/USDT' print("id: "+ hb.id + " name: " + hb.name) print("------ load_markets:") for item in hb.load_markets(): #print item pass print("------ markets keys:") print(list(hb.markets.keys())) for item in list(hb.markets.keys()): print(item) #pass print("------ symbols:") for item in hb.symbols:
def __init__(self): self.exchange = ccxt.huobipro() # 创建交易所 self.exchange.apiKey = apikey.huobi_apiKey_ro # 此处加上自己的apikey和secret,都需要开通交易权限 self.exchange.secret = apikey.huobi_secret_ro self.source_exchange = Exchange(self.exchange)
from datetime import timedelta import pandas as pd import smtplib from email.mime.text import MIMEText from email.header import Header import time huobi_exchange = ccxt.huobipro({ 'urls': { 'logo': 'https://user-images.githubusercontent.com/1294454/27766569-15aa7b9a-5edd-11e7-9e7f-44791f4ee49c.jpg', 'api': { 'market': 'https://api.huobi.io', 'public': 'https://api.huobi.io', 'private': 'https://api.huobi.io', 'zendesk': 'https://huobiglobal.zendesk.com/hc/en-us/articles', }, 'www': 'https://www.huobi.pro', 'referral': 'https://www.huobi.br.com/en-us/topic/invited/?invite_code=rwrd3', 'doc': 'https://github.com/huobiapi/API_Docs/wiki/REST_api_reference', 'fees': 'https://www.huobi.pro/about/fee/', } }) huobi_exchange.load_markets() while True: time_now = time.strftime("%H", time.localtime()) # 刷新 if time_now == "20": #此处设置每天定时的时间 now = datetime.now()
import ccxt exchange = ccxt.huobipro() # default id okcoin1 = ccxt.huobipro({'id': 'okcoin1'}) okcoin2 = ccxt.huobipro({'id': 'okcoin2'}) id = 'huobipro' btcchina = eval('ccxt.%s ()' % id) gdax = getattr(ccxt, 'gdax')() # from variable id exchange_id = 'huobipro' exchange_class = getattr(ccxt, exchange_id) exchange = exchange_class({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', 'timeout': 30000, 'enableRateLimit': True, })
def init_supported_exchanges(): objects = { "acx": ccxt.acx(), "aofex": ccxt.aofex(), "bequant": ccxt.bequant(), "bibox": ccxt.bibox(), "bigone": ccxt.bigone(), "binance": ccxt.binance(), "bitbank": ccxt.bitbank(), "bitbay": ccxt.bitbay(), "bitfinex": ccxt.bitfinex(), "bitflyer": ccxt.bitflyer(), "bitforex": ccxt.bitforex(), "bithumb": ccxt.bithumb(), "bitkk": ccxt.bitkk(), "bitmax": ccxt.bitmax(), "bitstamp": ccxt.bitstamp(), "bittrex": ccxt.bittrex(), "bitz": ccxt.bitz(), "bl3p": ccxt.bl3p(), "bleutrade": ccxt.bleutrade(), "braziliex": ccxt.braziliex(), "btcalpha": ccxt.btcalpha(), "btcbox": ccxt.btcbox(), "btcmarkets": ccxt.btcmarkets(), "btctradeua": ccxt.btctradeua(), "bw": ccxt.bw(), "bybit": ccxt.bybit(), "bytetrade": ccxt.bytetrade(), "cex": ccxt.cex(), "chilebit": ccxt.chilebit(), "coinbase": ccxt.coinbase(), "coinbasepro": ccxt.coinbasepro(), "coincheck": ccxt.coincheck(), "coinegg": ccxt.coinegg(), "coinex": ccxt.coinex(), "coinfalcon": ccxt.coinfalcon(), "coinfloor": ccxt.coinfloor(), "coinmate": ccxt.coinmate(), "coinone": ccxt.coinone(), "crex24": ccxt.crex24(), "currencycom": ccxt.currencycom(), "digifinex": ccxt.digifinex(), "dsx": ccxt.dsx(), "eterbase": ccxt.eterbase(), "exmo": ccxt.exmo(), "exx": ccxt.exx(), "foxbit": ccxt.foxbit(), "ftx": ccxt.ftx(), "gateio": ccxt.gateio(), "gemini": ccxt.gemini(), "hbtc": ccxt.hbtc(), "hitbtc": ccxt.hitbtc(), "hollaex": ccxt.hollaex(), "huobipro": ccxt.huobipro(), "ice3x": ccxt.ice3x(), "independentreserve": ccxt.independentreserve(), "indodax": ccxt.indodax(), "itbit": ccxt.itbit(), "kraken": ccxt.kraken(), "kucoin": ccxt.kucoin(), "lakebtc": ccxt.lakebtc(), "latoken": ccxt.latoken(), "lbank": ccxt.lbank(), "liquid": ccxt.liquid(), "livecoin": ccxt.livecoin(), "luno": ccxt.luno(), "lykke": ccxt.lykke(), "mercado": ccxt.mercado(), "oceanex": ccxt.oceanex(), "okcoin": ccxt.okcoin(), "okex": ccxt.okex(), "paymium": ccxt.paymium(), "poloniex": ccxt.poloniex(), "probit": ccxt.probit(), "southxchange": ccxt.southxchange(), "stex": ccxt.stex(), "surbitcoin": ccxt.surbitcoin(), "therock": ccxt.therock(), "tidebit": ccxt.tidebit(), "tidex": ccxt.tidex(), "upbit": ccxt.upbit(), "vbtc": ccxt.vbtc(), "wavesexchange": ccxt.wavesexchange(), "whitebit": ccxt.whitebit(), "yobit": ccxt.yobit(), "zaif": ccxt.zaif(), "zb": ccxt.zb() } return objects
def get_symbol_list(exchange): market = exchange.load_markets() market = pd.DataFrame(market).T symbol_list = list(market['symbol']) return symbol_list def get_today_start_time(): yesterday_date = datetime.date.today() - datetime.timedelta(days=1) start_time = str(yesterday_date) + ' 00:00:00' return start_time ##============================================ 设定参数 error_list = [] exchange_list = [ccxt.okex(), ccxt.huobipro(), ccxt.binance()] time_interval_list = ['5m', '15m'] path = r"C:\Users\dongx\PycharmProjects\bit_coin_2020\data\history_candle_data" start_time = get_today_start_time() # start_time = '2020-01-01 00:00:00' ##============================================ # 抓取USDT相关的数据对 for exchange in exchange_list: # 设定 交易对 symbols = get_symbol_list(exchange) for symbol in symbols: if symbol.endswith('/USDT') is False: continue # 遍历时间周期
def main(): chicang = 0 # 持仓标识-1,0,1 chicang_amount = 0 # 持仓数量 while True: # 参数 exchange = ccxt.huobipro() # 创建交易所 exchange.apiKey = '' exchange.secret = '' exchange.load_markets() symbol = 'ETH/USDT' # 交易品种 base_coin = symbol.split('/')[-1] # 基础货币 trade_coin = symbol.split('/')[0] # 交易货币 strategy = real_time_signal_swing # 策略名称 strategy2 = 'real_time_signal_swing' # 策略名称 para = [20, 6, 14, 50, 50, 2] # 策略参数 time_interval = '1m' # 运行间隔时间 # 第一步:更新账户信息 成功 while True: try: balance = exchange.fetch_balance() # 获取普通exchange交易账户数据 # print(balance) break except: continue base_coin_amount = float(balance[base_coin]['total']) trade_coin_amount = float(balance[trade_coin]['total']) print('当前资产:\n', base_coin, base_coin_amount, trade_coin, trade_coin_amount) # 也就相当于现货账户的持仓 for i in exchange.fetch_accounts(): if i['type'] == 'spot': # 现货账户号 spot_id = i['id'] if i['type'] == 'super-margin': # 杠杆账户号 margin_id = i['id'] balance_margin = exchange.fetch_balance({'id': margin_id}) total_btc = balance_margin['total']['BTC'] # BTC总量 total_usdt = balance_margin['total']['USDT'] # USDT总量 use_btc = balance_margin['used']['BTC'] # BTC已用数量 use_usdt = balance_margin['used']['USDT'] # USDT已用数量 free_btc = balance_margin['free']['BTC'] # BTC可用数量 free_usdt = balance_margin['free']['USDT'] # USDT可用数量 # 第二步:获取实时数据 # sleep直到运行时间 run_time = next_run_time(time_interval) print('睡眠:', ((run_time - datetime.datetime.now()).seconds), '秒') time.sleep(max( 0, (run_time - datetime.datetime.now()).seconds)) # 若sleep时间小于0,则会报错,这里是为了不报错 # 这个方法非常经典 while True: if datetime.datetime.now() < run_time: continue else: break # 获取实时数据 n = 0 while True: df = get_exchange_candle_data(exchange, symbol, time_interval) # 判断是否包含最新的数据 _temp = df[df['candle_begin_time_GTM8'] == ( run_time - datetime.timedelta(minutes=int(time_interval.strip('m'))) )] # 因为当前时间的K线的开始时间是time_interval分钟之前 if _temp.empty and n < 10: n += 1 continue else: print('获取到最新数据') break if n == 10: print('最近' + time_interval + '周期没有数据') # 第三步:实盘获取实盘交易信号 signal = real_time_signal_swing( chicang, df, para) # 参数:当前持仓方向-1、0、1;止损比例;数据;策略参数(可选) print('最新信号是:', signal) # 获取当前持仓数量 print('币币账户当前持仓品种:', base_coin, '持仓数量:', base_coin_amount) print('币币账户当前持仓品种:', trade_coin, '持仓数量:', trade_coin_amount) # print('杠杆账户当前持仓品种:', base_coin, '持仓数量:', total_usdt) # print('杠杆账户当前持仓品种:', trade_coin, '持仓数量:', total_btc) # exit() # signal = 1 # 测试用 # chicang = 0 # 测试用 # chicang_amount = 0.01 # 默认交易数量 # 开多单 if signal == 1: if chicang == 0: # 若没有持仓 print("开多单") # 获取最新卖一价格 buy_price = exchange.fetch_ticker(symbol)['ask'] # 计算买入数量,数量是指BTC的数量,不是USDT的数量 # buy_amount = base_coin_amount / buy_price * 3.3 * 0.1 # 按比例开仓 buy_amount = 0.01 # 下单,只限于币币交易 place_order(exchange, order_type='exchange limit', buy_or_sell='buy', symbol=symbol, price=round(buy_price * 1.001, 2), amount=buy_amount) print(symbol, '155开多单 价格:' + str(buy_price) + ' 数量:' + str(buy_amount)) send_dingding_msg('开仓报告:\n策略名称:' + strategy2 + '\n交易对:' + symbol + '\n开多单 价格:' + str(buy_price) + ' \n数量:' + str(buy_amount)) chicang_amount = buy_amount # exit() elif chicang == -1: # 若有空单持仓 print("平空单,开多单") # 平仓 buy_price = exchange.fetch_ticker(symbol)['ask'] # 获取卖一价格 print( symbol, '166开多单 价格:' + str(buy_price) + ' 数量:' + str(chicang_amount)) place_order(exchange, order_type='exchange limit', buy_or_sell='buy', symbol=symbol, price=round(buy_price * 1.005, 2), amount=chicang_amount) send_dingding_msg('平仓报告:\n策略名称:' + strategy2 + '\n交易对:' + symbol + '\n平空单 价格:' + str(buy_price) + ' \n数量:' + str(chicang_amount)) # 获取账户信息 while True: try: # balance = exchange.fetch_balance() # 获取普通exchange交易账户数据 balance_margin = exchange.fetch_balance( {'type': 'trading'}) # 获取margin账户资产,这是bitfinex交易所特有的 break except: continue base_coin_amount = float(balance_margin[base_coin]['total']) # 获取最新买一价格 buy_price = exchange.fetch_ticker(symbol)['ask'] # 计算买入数量 # buy_amount = base_coin_amount / buy_price * 3.3 * 0.1 buy_amount = 0.01 # 开仓 place_order(exchange, order_type='exchange limit', buy_or_sell='buy', symbol=symbol, price=round(buy_price * 1.005, 2), amount=buy_amount) print(symbol, '185开多单 价格:' + str(buy_price) + ' 数量:' + str(buy_amount)) send_dingding_msg('开仓报告:\n策略名称:' + strategy2 + '\n交易对:' + symbol + '\n开多单 价格:' + str(buy_price) + ' \n数量:' + str(buy_amount)) chicang_amount = buy_amount chicang = 1 # 持仓标记为持有多单 # 开空单 if signal == -1: if chicang == 0: # 若没有持仓 print("开空单") # 获取最新买一价格 sell_price = exchange.fetch_ticker(symbol)['bid'] # 计算卖出数量,这里的计算方式需要优化 # sell_amount = base_coin_amount / buy_price * 3.3 * 0.1 sell_amount = 0.01 # 下单开仓 place_order(exchange, order_type='exchange limit', buy_or_sell='sell', symbol=symbol, price=round(sell_price * 0.995, 2), amount=sell_amount) print( symbol, '200开空单 价格:' + str(sell_price) + ' 数量:' + str(sell_amount)) send_dingding_msg('开仓报告:\n策略名称:' + strategy2 + '\n交易对:' + symbol + '\n开空单 价格:' + str(sell_price) + ' \n数量:' + str(sell_amount)) chicang_amount = sell_amount elif chicang == 1: # 若有多单持仓 print("平多单,开空单") # 获取最新买一价格 sell_price = exchange.fetch_ticker(symbol)['bid'] # 下单平仓 place_order(exchange, order_type='exchange limit', buy_or_sell='sell', symbol=symbol, price=round(sell_price * 0.995, 2), amount=chicang_amount) print( symbol, '206平多单 价格:' + str(sell_price) + ' 数量:' + str(chicang_amount)) send_dingding_msg('平仓报告:\n策略名称:' + strategy2 + '\n交易对:' + symbol + '\n平多单 价格:' + str(sell_price) + ' \n数量:' + str(chicang_amount)) # 获取账户信息 while True: try: # balance = exchange.fetch_balance() # 获取普通exchange交易账户数据 balance_margin = exchange.fetch_balance( {'type': 'trading'}) # 获取margin账户资产,这是bitfinex交易所特有的 break except: continue base_coin_amount = float(balance_margin[base_coin]['total']) # 获取最新买一价格 sell_price = exchange.fetch_ticker(symbol)['bid'] # 计算买入数量 # sell_amount = base_coin_amount / buy_price * 3.3 * 0.1 sell_amount = 0.01 # 开仓 place_order(exchange, order_type='exchange limit', buy_or_sell='sell', symbol=symbol, price=round(sell_price * 0.995, 2), amount=sell_amount) print( symbol, '224开空单 价格:' + str(sell_price) + ' 数量:' + str(sell_amount)) send_dingding_msg('开仓报告:\n策略名称:' + strategy2 + '\n交易对:' + symbol + '\n开空单 价格:' + str(sell_price) + ' \n数量:' + str(sell_amount)) chicang_amount = sell_amount chicang = -1 # 持仓标记为持有空单 # 平仓 if signal == 0: if chicang == 1: # 若有多单持仓 print('平多单') # 获取最新买一价格 sell_price = exchange.fetch_ticker(symbol)['bid'] # 下单 place_order(exchange, order_type='exchange limit', buy_or_sell='sell', symbol=symbol, price=round(sell_price * 0.995, 2), amount=chicang_amount) print( symbol, '236平多仓 价格:' + str(sell_price) + ' 数量:' + str(chicang_amount)) send_dingding_msg('平仓报告:\n策略名称:' + strategy2 + '\n交易对:' + symbol + '\n平多单 价格:' + str(sell_price) + ' \n数量:' + str(chicang_amount)) if chicang == -1: # 若有空单持仓 print('平空单') # 获取最新卖一价格 buy_price = exchange.fetch_ticker(symbol)['ask'] # 下单 place_order(exchange, order_type='exchange limit', buy_or_sell='buy', symbol=symbol, price=round(buy_price * 1.005, 2), amount=chicang_amount) print( symbol, '244平空仓 价格:' + str(buy_price) + ' 数量:' + str(chicang_amount)) send_dingding_msg('平仓报告:\n策略名称:' + strategy2 + '\n交易对:' + symbol + '\n平空单 价格:' + str(buy_price) + ' \n数量:' + str(chicang_amount)) chicang = 0 # 持仓标记为没有持仓 # 本次交易结束 print('=====本次运行完毕\n')
from statistics_model.orm_tables import * with open("../config/config.json", 'r') as config_file: config = json.load(config_file) apiKey = config["api_config"]["apiKey"] secret = config["api_config"]["secret"] password = config["api_config"]["password"] exchange_name = config["exchange_name"] use_database = config["use_database"] assets_to_buy = config["assets_to_buy"] transaction_fee = float(config["transaction_fee"]) if exchange_name == "okex": exchange = ccxt.okex3() elif exchange_name == "huobi": exchange = ccxt.huobipro() password = None else: exchange = None print("暂时不支持{}交易所".format(exchange_name)) exit() trading_executor = TradingExecutor(exchange=exchange, api_key=apiKey, secret=secret, password=password) if use_database: with open("../config/database.json", 'r') as database_file: database_config = json.load(database_file) user = database_config["user"] password = database_config["password"]
# coding=utf-8 import ccxt from pprint import pprint import time # 火币的密钥 huoBi = ccxt.huobipro({ 'apiKey': 'dqnh6tvdf3-1592a8fc-728890ad-4d2e8', 'secret': '2333e4d3-c07ff5aa-b00f3dc9-d275b', }) # 获取XRP的价格 eosPrice = huoBi.fetch_ticker('EOS/USDT')['last'] print("当前价格XRP:", eosPrice) balance = huoBi.fetch_balance() usdtBalance = balance['USDT']['free'] print("余额USDT:", usdtBalance) # 下单参数 order_symbol = 'EOS/USDT' # 交易对 order_type = 'limit' # 订单类型:限价单 order_side = 'buy' # 下单方向 order_price = eosPrice - 0.01 # 下单价格 3.43 order_amount = 6 / eosPrice # 下单数量 x # 单个网格交易程序 # 下一个订单,循环监控订单状态,如果买单成交,则下一个买单,如果卖单成交,就下一个买单 takeOrder = huoBi.create_order(order_symbol, order_type, order_side, order_amount, order_price) # 开始下单 takeOrder_id = takeOrder['id'] # 获得线上id takeOrder_price = takeOrder['price'] # 获得线上订单价格