Example #1
0
 def log(self, content):
     if len(self.dict_data) > 0:
         content = self.dict_data['date'] + '----' + str(
             self.dict_data['close']) + '----' + content
     Base.txt_write(self.symbol, content)
     self.log_content = content
     print(content)
Example #2
0
def collect_to_csv(symbol='BTCUSDT', period='1m', timestamp=1528992000):
    # path1m=os.path.abspath('.') + '\\' + period + '_' + str(symbol).lower()+ '\\'
    dir1m = os.path.abspath('.') + '/' + period + '_' + str(
        symbol).lower() + '/'
    while timestamp < time.time() - 86400:
        # 生成币安url
        url = 'https://api.binance.com/api/v1/klines?symbol=' + symbol + '&interval=' + period + '&startTime=' + str(
            timestamp) + '000&limit=1000'
        # 获取json列表
        list_kline = Base.request_get(url)
        # 转换成df格式
        df = list_to_df(list_kline)
        # 保存文件
        if period == '1m':
            if not os.path.exists(dir1m):
                os.mkdir(dir1m)
                log('创建文件夹,以便保存csv文件' + dir1m)
            path = dir1m + str(df.iloc[0, 0]) + ".csv"
            timestamp = df.iloc[-1, 0] + 60
        else:
            path = str(symbol).lower() + 'merge1d.csv'
            timestamp = df.iloc[-1, 0] + 60 * 60 * 24
        df.to_csv(path, encoding="utf-8")
        log(Base.timestamp_to_date(df.iloc[0, 0]) + ' 保存成功 ' + str(path))
        time.sleep(1)
    # 合并分钟
    if period == '1m':
        merge1m(dir1m, symbol)
Example #3
0
def list_to_df(list_kline):
    # 遍历加入date
    for i in range(len(list_kline)):
        list_kline[i][0] = int(list_kline[i][0] / 1000)
        date = Base.timestamp_to_date(list_kline[i][0])
        list_kline[i].append(date)
    # 创建df
    df = pd.DataFrame(list_kline)
    # 去掉不需要数据
    df.drop([6, 7, 8, 9, 10, 11], axis=1, inplace=True)
    # 设置列名
    df.columns = ['timestamp', 'open', 'high', 'low', 'close', 'vol', 'date']
    # 转换数据类型
    df['timestamp'] = df['timestamp'].astype(int)
    df['open'] = df['open'].astype(float)
    df['high'] = df['high'].astype(float)
    df['low'] = df['low'].astype(float)
    df['close'] = df['close'].astype(float)
    df['vol'] = df['vol'].astype(float)
    df['date'] = df['date'].astype(str)
    # 掉换列位置
    list_columns = ['date', 'timestamp', 'open', 'high', 'low', 'close', 'vol']
    df = df[list_columns]
    # 设置日期为索引
    df.set_index('date', inplace=True)
    return df
Example #4
0
 def __init__(self,
              date_start='2018-06-10 23:40',
              date_end='2018-09-10 23:40'):
     self.date = '1980'
     self.coinname = 'btc'
     Base.txt_remove(self.coinname + '.txt')
     print('创建策略完成:' + 'PolicyInfinite' + self.coinname)
     # 实例化模型
     self.model = InfiniteModel()
     # 定义容器
     self.dict_account = {
         'quanyi': 0,
         'money': 10000,
         'paper_duo': 0,
         'paper_kong': 0,
         'priceaver_duo': 0,
         'priceaver_kong': 0,
         'rate_margin': 0
     }
     self.dict_record = {
         'fund_start': 0,
         'quanyi_start': 0,
         'price_start': 0,
         'paper_chong': 0,
         'paper_aver': 0,
         'timestampRecord': 0,
         'timestampNow': 0,
         'list_price': [],
         'list_shouyi': [],
         'list_quanyi': [],
         'list_fund': []
     }
     self.dict_param = {
         'date_start': date_start,
         'date_end': date_end,
         'isStop': False,
         'wg_num': 100,
         'jiange_wg': 0.01,
         'jiange_sell': 0.02,
     }
     self.list_wg = []
     self.dict_close = {}
     self.dict_open = {}
     self.main(self.coinname)
Example #5
0
def collect_to_csv(symbol='BTCUSDT', timestamp=1528992000):
    dir1m = os.path.abspath('.') + '/' + str(symbol).lower() + '/'
    while timestamp < time.time() - 86400:
        # 生成币安url
        url = 'https://api.binance.com/api/v1/klines?symbol=' + symbol + '&interval=1m&startTime=' + str(
            timestamp) + '000&limit=1000'
        # 获取json列表
        list_kline = Base.request_get(url)
        # 转换成df格式
        df = list_to_df(list_kline)
        # 保存文件
        if not os.path.exists(dir1m):
            os.mkdir(dir1m)
            log('创建文件夹,以便保存csv文件' + dir1m)
        path = dir1m + Base.timestamp_to_date_pure(int(df.iloc[0, 0])) + ".csv"
        timestamp = df.iloc[-1, 0] + 60
        df.to_csv(path, encoding="utf-8")
        log(Base.timestamp_to_date(df.iloc[0, 0]) + ' 保存成功 ' + str(path))
        time.sleep(1)
Example #6
0
 def update_online_profit(self, price, type=None):
     res = 0
     contract_size = self.param['contract_size']
     for i in range(len(self.list_wg)):
         id_wg = self.list_wg[i]['id_wg']
         price_wg = self.list_wg[i]['price_wg']
         paper = self.list_wg[i]['paper']
         status = self.list_wg[i]['status']
         price_close = self.list_wg[i]['price_close']
         online_profit = 0
         if type == 'duo':
             if status == 'duo_closeing' or status == 'duo_ok':
                 online_profit = Base.get_online_profit(
                     price_wg, price, paper, contract_size, True)
         elif type == 'kong':
             if status == 'kong_closeing':
                 online_profit = Base.get_online_profit(
                     price_wg, price, paper, contract_size, False)
         else:
             if status == 'duo_closeing' or status == 'duo_ok':
                 online_profit = Base.get_online_profit(
                     price_wg, price, paper, contract_size, True)
             elif status == 'kong_closeing' or status == 'kong_ok':
                 online_profit = Base.get_online_profit(
                     price_wg, price, paper, contract_size, False)
             elif status == 'duo_close':
                 online_profit = Base.get_online_profit(
                     price_wg, price_close, paper, contract_size, True)
             elif status == 'kong_close':
                 online_profit = Base.get_online_profit(
                     price_wg, price_close, paper, contract_size, False)
             self.update_data(id_wg, {'online_profit': online_profit})
         res += online_profit
     return round(res, 4)
Example #7
0
 def main(self, coinname):
     # 获取数据文件列表
     klineFileList = self.model.getKlineFileList(coinname)
     # 获取运行期间
     timestamp_start = Base.date_to_timestamp(self.dict_param['date_start'])
     timestamp_end = Base.date_to_timestamp(self.dict_param['date_end'])
     self.dict_record['timestampNow'] = timestamp_start
     # 获取面值
     mianzhi = Base.get_contract_size(coinname)
     # 遍历listKline
     for klineFile in klineFileList:
         df_1m = pd.read_csv(klineFile, index_col=0).reset_index()
         for i in range(len(df_1m)):
             timestamp = int(df_1m.loc[i, 'timestamp'])
             if timestamp_start <= self.dict_record[
                     'timestampNow'] < timestamp <= timestamp_end:
                 # 解析数据
                 self.dict_record['timestampNow'] = timestamp
                 date = df_1m.loc[i, 'date']
                 self.date = df_1m.loc[i, 'date']
                 open = float(df_1m.loc[i, 'open'])
                 high = float(df_1m.loc[i, 'high'])
                 low = float(df_1m.loc[i, 'low'])
                 close = float(df_1m.loc[i, 'close'])
                 # 执行循环
                 self.loop(timestamp, date, open, high, low, close, mianzhi)
             elif timestamp > timestamp_end:
                 # 总结数据
                 self.dict_param['isStop'] = True
                 print('end')
                 break
         if self.dict_param['isStop']:
             break
     #总结
     self.zongjie()
     return
Example #8
0
def merge1m(path, symbol):
    df = None
    symbol = str(symbol).lower()
    list_csv = sorted(os.listdir(path), reverse=False)
    is_creat = False
    for i in range(len(list_csv)):
        csv = list_csv[i]
        if int(str(csv)[:10]) > Base.date_to_timestamp('2018-09-14 08:00'):
            print('i=' + str(i) + '   ' + csv)
            if not is_creat:
                is_creat = True
                df = pd.read_csv(path + csv, index_col=0)
            else:
                df = df.append(pd.read_csv(path + csv, index_col=0))
                # 如果超过104.8w条,就跳出循环
                if len(df) > 1048000:
                    break
    # 去重
    df.drop_duplicates(keep='last', inplace=True)
    df.to_csv(symbol + 'merge1m.csv', encoding="utf-8")
    print(symbol + '合并完成')
Example #9
0
def get_atr(coin, path):
    atr_0615 = {
        'btc': 378.52,
        'eth': 45.54,
        'eos': 1.5553,
        'ltc': 8.71,
        'etc': 1.6945,
    }
    df = pd.read_csv(path, index_col=0)
    df = df.reset_index()
    df['yesterday_close'] = df['close'].shift(1)
    # 计算tr
    df['tr'] = 0
    print(df)
    print(df)
    for i in range(len(df)):
        df.loc[i, 'tr'] = max(
            abs(df.loc[i, 'high'] - df.loc[i, 'low']),
            abs(df.loc[i, 'high'] - df.loc[i, 'yesterday_close']),
            abs(df.loc[i, 'yesterday_close'] - df.loc[i, 'low']))
    # 计算atr
    df['atr'] = 0
    for i in range(len(df)):
        if i == 0:
            df.loc[i, 'atr'] = atr_0615[coin]
        else:
            if coin == 'etc' and df.loc[i,
                                        'timestamp'] == Base.date_to_timestamp(
                                            '2018-06-25 08:00'):
                df.loc[i, 'atr'] = atr_0615[coin]
            df.loc[i, 'atr'] = round(
                (df.loc[i - 1, 'atr'] * 13 + df.loc[i, 'tr']) / 14, 4)
    # 删除多余的列
    df.drop(columns=['yesterday_close', 'tr'], inplace=True)
    df.to_csv(path, index=None, encoding="utf-8")
    print(path + '增加atr成功')
Example #10
0
 def main(self, date_start, date_end, param=None):
     if param is None:
         param = {}
         return
     # 初始化容器
     self.coin = str(param['symbol']).lower()[0:3]
     self.symbol = param['symbol']
     self.param = param
     self.param['contract_size'] = Base.get_contract_size(self.coin)
     self.list_wg_trade = []
     self.dict_acc = {
         'money': 10000,
         'margin_balance': 0,
         'fund_start': 0,
         'price_start': 0,
         'lun_price_start': 0,
         'lun_timestamp_start': 0,
         'lun_margin_balance_start': 0,
         'lun_fund_start': 0,
     }
     self.dict_record = {
         'timestamp': 0,
         'list_margin_balance': [],
         'list_rate_kline': [],
         'list_rate_profit': [],
         'list_fund': [],
         'list_money': [],
         'list_rate_paper_duo': [],
         'list_rate_paper_kong': [],
         'list_rate_paper': [],
     }
     Base.txt_remove(self.symbol + '.txt')
     self.log('进入策略main函数,准备容器完成,param=' + str(param))
     self.log('dict_acc=' + str(self.dict_acc))
     # 遍历数据
     path = os.path.abspath(
         os.getcwd()) + '/klineok/' + self.coin + '1m1dok.csv'
     df_1m = pd.read_csv(path, index_col=0).reset_index()
     for i in range(len(df_1m)):
         timestamp = int(df_1m.loc[i, 'timestamp'])
         if Base.date_to_timestamp(
                 date_start) < timestamp < Base.date_to_timestamp(date_end):
             close = float(df_1m.loc[i, 'close'])
             high = float(df_1m.loc[i, 'high'])
             low = float(df_1m.loc[i, 'low'])
             atr = float(df_1m.loc[i, 'atr'])
             self.dict_data = {
                 'date': df_1m.loc[i, 'date'],
                 'timestamp': timestamp,
                 'open': float(df_1m.loc[i, 'open']),
                 'high': high,
                 'low': low,
                 'close': close,
                 'day_date': df_1m.loc[i, 'day_date'],
                 'ma60': float(df_1m.loc[i, 'ma60']),
                 'ma91': float(df_1m.loc[i, 'ma91']),
                 'atr': atr,
             }
             # 判断是否首次遍历
             if self.dict_acc['price_start'] == 0:
                 self.dict_acc['price_start'] = close
                 self.dict_acc['fund_start'] = self.dict_acc['money']
                 continue
             # 判断买币
             if self.dict_acc['margin_balance'] == 0 and self.dict_acc[
                     'money'] == self.dict_acc['fund_start']:
                 self.trade_coin(close,
                                 round(self.dict_acc['money'] / close, 4),
                                 True)
                 continue
             # 判断创建网格
             if len(self.list_wg_trade) <= 1:
                 self.creat_wg_trade(close, self.dict_data['ma91'])
                 continue
             # 合约交易
             self.trade_contract(high, low, close,
                                 self.param['contract_size'])
             # 记录日志
             self.record(close)
         elif timestamp > Base.date_to_timestamp(date_end):
             break
         elif len(self.dict_record['list_rate_profit']) > 0:
             if self.dict_record['list_rate_profit'][-1] < -30:
                 Base.txt_write(
                     './result/' + 'index',
                     'err' + str(self.dict_record['list_rate_profit'][-1]))
                 break
     # 绘图
     Base.txt_write(
         './result/' + 'index',
         '通过,最大回撤' + str(min(self.dict_record['list_rate_profit'])))
     Base.chart('margin_balance',
                self.dict_record['list_margin_balance'],
                path=self.path)
     Base.chart('rate_kline_rate_profit',
                self.dict_record['list_rate_kline'],
                self.dict_record['list_rate_profit'],
                path=self.path)
     Base.chart('fund_money',
                self.dict_record['list_fund'],
                self.dict_record['list_money'],
                path=self.path)
     Base.chart('paper_duo_paper_kong_paper',
                self.dict_record['list_rate_paper_duo'],
                self.dict_record['list_rate_paper_kong'],
                self.dict_record['list_rate_paper'],
                path=self.path)
     Base.wg_csv('final', int(self.dict_data['timestamp']),
                 self.list_wg_trade, self.path)
Example #11
0
    def trade_contract(self, high, low, close, contract_size):
        # 交易
        for i in range(len(self.list_wg_trade)):
            # 获取字段
            id_wg = self.list_wg_trade[i]['id_wg']
            price_wg = self.list_wg_trade[i]['price_wg']
            paper_wg = self.list_wg_trade[i]['paper_wg']
            status = self.list_wg_trade[i]['status']
            price_close = self.list_wg_trade[i]['price_close']
            is_shun = self.list_wg_trade[i]['is_shun']
            if status == 'duo_ing' and low < price_wg:
                self.list_wg_trade[i]['date'] = self.dict_data['date']
                self.list_wg_trade[i]['status'] = 'duo_ok'
                self.list_wg_trade[i]['price_close'] = round(
                    price_wg * 0.01 * (100 + self.param['profit_close']), 3)
                if is_shun:
                    self.list_wg_trade[i]['price_close'] = 0
                self.log(
                    str(id_wg) + '开多成功,low=' + str(low) + '<price_wg=' +
                    str(price_wg) + ',委托平空价' +
                    str(self.list_wg_trade[i]['price_close']))
                continue
            elif status == 'duo_wait' and high > price_wg:
                self.list_wg_trade[i]['status'] = 'duo_ing'
                self.log(str(id_wg) + '委托多单,price_wg=' + str(price_wg))
                continue
            elif status == 'kong_ing' and high > price_wg:
                self.list_wg_trade[i]['date'] = self.dict_data['date']
                self.list_wg_trade[i]['status'] = 'kong_ok'
                self.list_wg_trade[i]['price_close'] = round(
                    price_wg * 0.01 * (100 - self.param['profit_close']), 3)
                if is_shun:
                    self.list_wg_trade[i]['price_close'] = 0
                self.log(
                    str(id_wg) + '开空成功,high=' + str(high) + '>price_wg=' +
                    str(price_wg) + ',委托平空价' +
                    str(self.list_wg_trade[i]['price_close']))
                continue
            elif status == 'kong_wait' and low < price_wg:
                self.list_wg_trade[i]['status'] = 'kong_ing'
                self.log(str(id_wg) + '委托空单,price_wg=' + str(price_wg))
                continue
            elif status == 'duo_ok' or status == 'kong_ok' or status == 'hedge_ok':

                self.list_wg_trade[i]['profit'] = Base.get_online_profit(
                    price_wg, close, paper_wg, contract_size,
                    status == 'duo_ok')
                if status == 'duo_ok' and high > price_close and not is_shun:
                    profit = Base.get_online_profit(price_wg, price_close,
                                                    paper_wg, contract_size,
                                                    True)
                    self.list_wg_trade[i]['times_close'] += 1
                    self.list_wg_trade[i]['profit_sum'] = round(
                        self.list_wg_trade[i]['profit_sum'] + profit, 4)
                    self.list_wg_trade[i]['status'] = 'duo_wait'
                    self.list_wg_trade[i]['price_close'] = 0
                    self.log(
                        str(id_wg) + '平多完成,开价' + str(price_wg) + 'high' +
                        str(high) + '>平仓' + str(price_close) + '收益' +
                        str(profit) + '累计收益' +
                        str(self.list_wg_trade[i]['profit_sum']))
                    self.list_wg_trade[i]['profit'] = 0
                elif status == 'kong_ok' and low < price_close and not is_shun:
                    profit = Base.get_online_profit(price_wg, price_close,
                                                    paper_wg, contract_size,
                                                    False)
                    self.list_wg_trade[i]['times_close'] += 1
                    self.list_wg_trade[i]['profit_sum'] = round(
                        self.list_wg_trade[i]['profit_sum'] + profit, 4)
                    self.list_wg_trade[i]['status'] = 'kong_wait'
                    self.list_wg_trade[i]['price_close'] = 0
                    self.log(
                        str(id_wg) + '平空完成,开价' + str(price_wg) + 'low' +
                        str(low) + '<平仓' + str(price_close) + '收益' +
                        str(profit) + '累计收益' +
                        str(self.list_wg_trade[i]['profit_sum']))
                    self.list_wg_trade[i]['profit'] = 0
Example #12
0
    def main(self, symbol, date_start, date_end, param=None):
        if param is None:
            param = {}
        coin = str(symbol).lower()[0:3]
        # 填充容器
        self.symbol = symbol
        self.param = param
        self.param['contract_size'] = Base.get_contract_size(coin)
        self.list_wg = []
        self.dict_acc = {
            'fund_start': 10000,
            'price_start': 0,
            'lun_timestamp_start': 0,
            'lun_margin_start': 0,
            'margin_balance': 0,
            'money': 10000,
            'record_timestamp': 0,
            'record_list_margin_balance': [],
            'record_list_fund': [],
            'record_list_rate_kline': [],
            'record_list_rate_profit': [],
            'record_list_rate_paper': [],
            'record_list_rate_paper_duo': [],
            'record_list_rate_paper_kong': []
        }
        Base.txt_remove(self.symbol + '.txt')
        self.log('进入策略main函数,准备容器完成,param=' + str(param))
        self.log('dict_acc=' + str(self.dict_acc))

        # 遍历数据
        path = os.path.abspath(os.getcwd()) + '/klineok/' + coin + '1m1dok.csv'
        df_1m = pd.read_csv(path, index_col=0).reset_index()
        for i in range(len(df_1m)):
            timestamp = int(df_1m.loc[i, 'timestamp'])
            if Base.date_to_timestamp(
                    date_start) < timestamp < Base.date_to_timestamp(date_end):
                close = float(df_1m.loc[i, 'close'])
                high = float(df_1m.loc[i, 'high'])
                low = float(df_1m.loc[i, 'low'])
                atr = float(df_1m.loc[i, 'atr'])
                self.dict_data = {
                    'date': df_1m.loc[i, 'date'],
                    'timestamp': timestamp,
                    'open': float(df_1m.loc[i, 'open']),
                    'high': high,
                    'low': low,
                    'close': close,
                    'day_date': df_1m.loc[i, 'day_date'],
                    'ma60': float(df_1m.loc[i, 'ma60']),
                    'ma91': float(df_1m.loc[i, 'ma91']),
                    'atr': atr,
                }

                if self.dict_acc['price_start'] == 0:
                    self.dict_acc['price_start'] = close
                margin_balance = self.dict_acc['margin_balance']
                contract_size = self.param['contract_size']
                paper_cover = int(margin_balance * close / contract_size)
                paper_each = max(1, round(paper_cover * self.param['paper'],
                                          2))
                self.check(close, timestamp)
                self.wg_trade(close, high, low, atr, timestamp, paper_each)
            elif timestamp > Base.date_to_timestamp(date_end):
                break
        # 绘图
        Base.chart('margin_balance',
                   self.dict_acc['record_list_margin_balance'])
        Base.chart('fund', self.dict_acc['record_list_fund'])
        Base.chart('kline_profit', self.dict_acc['record_list_rate_kline'],
                   self.dict_acc['record_list_rate_profit'])
        Base.chart('record_list_rate_paper',
                   self.dict_acc['record_list_rate_paper'])
        Base.chart('kline_paperduo_paperkong',
                   self.dict_acc['record_list_rate_kline'],
                   self.dict_acc['record_list_rate_paper_duo'],
                   self.dict_acc['record_list_rate_paper_kong'])
        Base.wg_csv('final', int(self.dict_data['timestamp']), self.list_wg)
Example #13
0
 def check(self, price, timestamp):
     # 买币卖币
     if self.dict_acc['margin_balance'] == 0 and self.dict_acc[
             'money'] == self.dict_acc['fund_start']:
         self.coin_trade(price, round(self.dict_acc['money'] / price, 4),
                         True)
     # 对冲交易
     if len(self.list_wg) == 0:
         self.cover_trade(price)
     # 更新账户权益
     self.dict_acc['margin_balance'] = self.dict_acc[
         'lun_margin_start'] + self.update_online_profit(price)
     # 更新最后一次交易记录
     num_duo_ing = self.count_status('duo_ing')
     num_kong_ing = self.count_status('kong_ing')
     num_duo_closeing = self.count_status('duo_closeing')
     num_kong_closeing = self.count_status('kong_closeing')
     if num_duo_ing == 0 and num_duo_closeing == 0:
         self.dict_record['last_price_duo'] = 99999
         self.dict_record['last_timestamp_duo'] = 0
     if num_kong_ing == 0 and num_kong_closeing == 0:
         self.dict_record['last_price_kong'] = 0
         self.dict_record['last_timestamp_kong'] = 0
     # 获取数据
     margin_balance = self.dict_acc['margin_balance']
     money = self.dict_acc['money']
     fund = round(margin_balance * price, 2)
     paper_kong_ok = self.get_sum_paper('kong_ok')
     paper_kong_closeing = self.get_sum_paper('kong_closeing')
     paper_duo_closeing = self.get_sum_paper('duo_closeing')
     # 计算收益率
     rate_kline = round(price / self.dict_acc['price_start'] * 100 - 100, 2)
     rate_fund = round(fund / self.dict_acc['fund_start'] * 100 - 100, 2)
     rate_profit = round(money / self.dict_acc['fund_start'] * 100, 2)
     rate_paper = paper_duo_closeing + paper_kong_closeing + paper_kong_ok
     # 记录列表信息
     if timestamp - self.dict_acc['record_timestamp'] > 60 * 60 * 8:
         self.dict_acc['record_timestamp'] = timestamp
         self.dict_acc['record_list_margin_balance'].append(margin_balance)
         self.dict_acc['record_list_fund'].append(fund)
         self.dict_acc['record_list_rate_kline'].append(rate_kline)
         self.dict_acc['record_list_rate_profit'].append(rate_profit)
         self.dict_acc['record_list_rate_paper'].append(rate_paper)
         self.dict_acc['record_list_rate_paper_duo'].append(
             paper_duo_closeing)
         self.dict_acc['record_list_rate_paper_kong'].append(
             paper_kong_closeing)
         # 输出记录
         note1 = '冲' + str(paper_kong_ok) + '多' + str(
             paper_duo_closeing) + '空' + str(
                 paper_kong_closeing) + '多浮' + str(
                     self.update_online_profit(price, 'duo')) + '空浮' + str(
                         self.update_online_profit(price, 'kong'))
         note11 = '多均' + str(self.get_price_aver(True)) + '空均' + str(
             self.get_price_aver(False))
         note2 = '权益' + str(round(
             margin_balance, 4)) + '资产' + str(fund) + '基准率' + str(
                 rate_kline) + '%收益率' + str(rate_profit) + '%'
         note3 = '本轮初始权益' + str(self.dict_acc['lun_margin_start'])
         self.log('记录' + note1 + note11 + note2)
     # 判断是否全平
     if rate_fund > self.param['stop_profit_all']:
         days_cost = round((self.dict_data['timestamp'] -
                            self.dict_acc['lun_timestamp_start']) / 86400,
                           2)
         Base.wg_csv('sell' + str(rate_fund) + 'days' + str(days_cost),
                     int(self.dict_data['timestamp']), self.list_wg)
         self.list_wg.clear()
         num_sell = round((fund - self.dict_acc['fund_start']) / price, 4)
         self.coin_trade(price, num_sell, False)
         self.check(price, timestamp)
Example #14
0
 def log(self, content):
     content = self.date + '---------' + content
     print(content)
     Base.txt_write(self.coinname + '.txt', content)
Example #15
0
 def loop(self, timestamp, date, open, high, low, close, mianzhi):
     if self.dict_account['quanyi'] == 0:
         # 买币
         self.dict_record['fund_start'] = self.dict_account['money']
         self.dict_account['quanyi'] = self.model.maibi(
             self.dict_account['money'], close)
         self.dict_account['money'] = 0
         self.dict_record['quanyi_start'] = self.dict_account['quanyi']
         self.dict_record['price_start'] = close
         m = '买币完成,权益=' + str(self.dict_account['quanyi'])
         self.log(m)
         #创建网格
         self.dict_record['paper_chong'], self.dict_record[
             'paper_aver'], self.list_wg = self.model.creat_wg(
                 close, self.dict_account['quanyi'], mianzhi, 100,
                 self.dict_param['jiange_wg'])
         self.log('对冲成功,格数' + str(len(self.list_wg)) + ',对冲张数' +
                  str(self.dict_record['paper_chong']) + ',每格张数' +
                  str(self.dict_record['paper_aver']))
     else:
         #交易
         for i in range(len(self.list_wg)):
             wg = self.list_wg[i]
             price_wg = wg['price_wg']
             paper_wg = wg['paper_wg']
             price_close = wg['price_close']
             status = wg['status']
             #计算价格比
             rate_price = close / price_wg
             #委托开多
             if status == 'duo_wait' and 1 < rate_price < 1.02:
                 self.list_wg[i]['status'] = 'duo_ing'
                 self.log('委托开多,price_wg=' + str(price_wg) + 'paper_wg=' +
                          str(paper_wg))
             elif status == 'duo_ing' and low < price_wg:
                 self.list_wg[i]['status'] = 'duo_ok'
                 self.log('开多成功,price_wg=' + str(price_wg) + 'paper_wg=' +
                          str(paper_wg))
                 self.list_wg[i]['status'] = 'duo_closeing'
                 self.list_wg[i]['price_close'] = round(
                     price_wg * (1 + self.dict_param['jiange_sell']), 4)
                 self.log('委托平多,price_close=' +
                          str(self.list_wg[i]['price_close']))
             elif status == 'duo_closeing':
                 #计算在线收益
                 shouyi = Base.get_online_profit(price_wg,
                                                 close,
                                                 paper_wg,
                                                 mianzhi,
                                                 duo=True)
                 self.list_wg[i]['shouyi'] = shouyi
                 if high > price_close:
                     #平多成功
                     shouyi = Base.get_online_profit(price_wg,
                                                     price_close,
                                                     paper_wg,
                                                     mianzhi,
                                                     duo=True)
                     self.list_wg[i]['status'] = 'duo_wait'
                     self.list_wg[i]['times_close'] += 1
                     self.list_wg[i]['shouyi_sum'] += shouyi
                     self.list_wg[i]['price_close'] = 0
                     self.list_wg[i]['shouyi'] = 0
                     self.log('平多成功,price_wg=' + str(price_wg) +
                              'price_close=' + str(price_close) +
                              'shouyi=' + str(shouyi))
                     self.dict_record['list_shouyi'].append(shouyi)
         #记录
         if timestamp - self.dict_record['timestampRecord'] > 60 * 60 * 12:
             self.dict_record['timestampRecord'] = timestamp
             wg_detail = self.model.get_listwg_detail(self.list_wg)
             self.dict_account[
                 'quanyi'] = self.dict_record['quanyi_start'] + wg_detail[
                     'shouyi_online'] + wg_detail['shouyi_ok']
             self.dict_account['fund'] = self.dict_account['quanyi'] * close
             self.dict_record['list_price'].append(close)
             self.dict_record['list_quanyi'].append(
                 self.dict_account['quanyi'])
             self.dict_record['list_fund'].append(self.dict_account['fund'])
             self.log('当前状态:' + date)
             self.log(str(wg_detail))