Exemple #1
0
def dump_history():
    frequency = '1m'
    days_before = 365 * 3
    key = 'VvD5-fMBfiZ9dlMtXP2pffHj'
    secret = 'jROi3UZ5q_hkVW2RnK3xbCQEnTzpLXcnbOdUCJTnQFrrdUgj'
    symbol = 'XBTUSD'
    file_name = "%s_%s_%sdays.txt" % (symbol, frequency, days_before)
    file_name = 'temp.txt'
    client = RestClient(False, key, secret, symbol)

    fp = open(file_name, 'w')
    start_time = datetime.utcnow() - timedelta(days=days_before)
    start_time = datetime(2020, 1, 29, 8, 57, tzinfo=tzutc())
    wanted_ones = ['open', 'close', 'low', 'high', 'volume', 'timestamp']
    while True:
        start_time = start_time.strftime("%Y-%m-%d %H:%M")
        filter = '{"symbol": "%s", "startTime": "%s"}' % (symbol, start_time)
        temp = client.trade_bucket(binSize=frequency,
                                   count=1000,
                                   filter=filter)
        ohlc = []
        for t in temp:
            d = {k: t[k] for k in wanted_ones}
            ohlc.append(str(d))
        sleep(2)
        fp.write('\n'.join(ohlc))
        fp.write('\n')
        if len(temp) < 1000:
            break
        start_time = temp[-1]['timestamp'] + timedelta(minutes=1)
        pass
    fp.close()
Exemple #2
0
def resbrk_parentchild(key, secret, product, frequency, child_frequency='5m'):
    client = RestClient(False, key, secret, product)
    symbol = BitMEXSymbol(product, client=client, frequency=frequency)

    fp = open('XBTUSD_1h_365days.txt', 'r')
    data = [
        eval(d.replace('datetime.datetime', 'datetime'))
        for d in fp.readlines()
    ]
    fp.close()
    parent_dataframe = symbol.fetch_data(datetime.utcnow(),
                                         data=data,
                                         frequency=frequency)

    fp = open('XBTUSD_5m_100days.txt', 'r')
    data = [
        eval(d.replace('datetime.datetime', 'datetime'))
        for d in fp.readlines()
    ]
    fp.close()
    child_dataframe = symbol.fetch_data(datetime.utcnow(),
                                        data=data,
                                        frequency=child_frequency)

    # parent_dataframe = import_data(symbol, "XBTUSD_1h_365days.txt")
    bt = ResistanceBreakoutParentChildBackTest(parent_dataframe.iloc[-1 * 24 *
                                                                     30:],
                                               child_dataframe,
                                               frequency,
                                               child_frequency=child_frequency)
    bt.rolling_period = 15
    bt.min_profit = 50
    bt.min_loss = -100
    bt.volume_factor = 0.1
    bt.max_loss = -150

    # macd, macd_sig = bt.MACD(12,26,9)
    # bt.dataframe["macd"] = macd
    # bt.dataframe["macd_sig"] = macd_sig
    # bt.child_dataframe["rsi"] = bt.RSI(DF=bt.child_dataframe, n=10 * 14).copy()

    bt.setup()
    bt.run()

    sum = 0
    trades = []
    time_series = bt.dataframe.index.tolist()
    for r in bt.returns:
        signal, entry_p, exit_p, net, best_price, oi, ci = r
        # open_frame = bt.dataframe.iloc[oi]
        open_time = time_series[oi]
        # close_frame = bt.dataframe.iloc[ci]
        close_time = time_series[ci]
        frame = bt.dataframe.iloc[oi:ci + 1]
        child_frame = bt.child_dataframe[open_time:close_time]
        max_loss = -3 * int(entry_p / 150)
        sum += net - 14.5
        trades.append((net, signal, entry_p, exit_p, best_price, oi, ci, frame,
                       child_frame))
    return bt
Exemple #3
0
    def sample(key, secret):
        db = '/Users/jganesan/workspace/algotrading/symbols.sqlite3'
        conn = sqlite3.connect(db)
        key = "MjLgBPoZey_vp3rQ7uM0riqA"
        secret = "1AiC5B6cqs4hRSgBDPU_KyU3rSCyMiIrCoD1mkkT-LjP3ymJ"
        symbol = 'XBTUSD'
        frequency = '5m'
        client = client = RestClient(False, key, secret, symbol)
        xbt = BitMEXSymbol(symbol,
                           conn=conn,
                           client=client,
                           frequency=frequency)
        df1 = xbt.fetch_data(datetime.utcnow() - timedelta(days=3), count=740)
        xbt.write_to_db(df1)

        conn.close()

        s = ResistanceBreakoutBackTest(df)
        s.weighted = False
        s.rolling_period = 10
        s.min_profit = 13.5
        s.min_loss = -20
        s.setup()
        s.run()

        sum = 0
        for r in s.returns:
            sum += r[-1] - 13.5
Exemple #4
0
def resbrk_backtest(key, secret, product, frequency):
    client = RestClient(False, key, secret, product)
    symbol = BitMEXSymbol(product, client=client, frequency=frequency)
    # dataframe = pd.DataFrame(symbol.fetch_data(datetime.utcnow() - timedelta(days=3)))
    # dataframe = import_data(symbol, 'XBTUSD_1h_365days.txt')
    fp = open('XBTUSD_1h_365days.txt', 'r')
    data = [
        eval(d.replace('datetime.datetime', 'datetime'))
        for d in fp.readlines()
    ]
    fp.close()
    dataframe = symbol.fetch_data(datetime.utcnow(),
                                  data=data,
                                  frequency=frequency)
    res_bro = ResistanceBreakoutBackTest(dataframe.iloc[-1 * 24 * 30:])
    res_bro.rolling_period = 15
    # res_bro.min_profit = 50
    # res_bro.min_loss = -100
    # res_bro.max_loss = -150
    res_bro.volume_factor = 0.1
    res_bro.setup()
    res_bro.run()

    sum = 0
    trades = []
    time_series = res_bro.dataframe.index.tolist()
    max_loss = 0
    max_loss_frame = None
    loss_frames = []
    for r in res_bro.returns:
        signal, entry_p, exit_p, net, best_price, oi, ci = r
        max_loss = int(entry_p / 150) * -3
        sum += max(max_loss, net) - 14.5
        open_frame = res_bro.dataframe.iloc[oi]
        open_time = time_series[oi]
        close_frame = res_bro.dataframe.iloc[ci]
        close_time = time_series[ci]
        frame = res_bro.dataframe.iloc[oi:ci + 1]
        trades.append(
            (net, signal, entry_p, exit_p, best_price, oi, ci, frame))
        if net < max_loss:
            max_loss_frame = frame
            max_loss = net
        if net < 0:
            loss_frames.append(
                (net, signal, entry_p, exit_p, best_price, oi, ci, frame))

    print(sum)
    return res_bro
Exemple #5
0
def renkomacd_backtest(key, secret, product, frequency):
    client = RestClient(False, key, secret, product)
    symbol = BitMEXSymbol(product, client=client, frequency=frequency)
    # dataframe = pd.DataFrame(symbol.fetch_data(datetime.utcnow() - timedelta(days=365)))
    dataframe = import_data(symbol, 'XBTUSD_5m_100days.txt')
    backtest = RenkoMACDBackTest(dataframe.iloc[-1 * 24 * 30:])
    # backtest.atr_period = 60
    # backtest.slope_period = 3
    # backtest.macd_array = (6, 15, 6)
    backtest.min_profit = 0
    backtest.min_loss = 0
    backtest.setup()
    backtest.run()

    sum = 0
    trades = []
    time_series = backtest.dataframe.index.tolist()
    max_loss = 0
    max_loss_frame = None
    loss_frames = []
    for r in backtest.returns:
        sum += max(-200, r[2]) - 14.5
        open_frame = backtest.dataframe.iloc[r[0]]
        open_time = time_series[r[0]]
        close_frame = backtest.dataframe.iloc[r[1]]
        close_time = time_series[r[1]]
        frame = backtest.dataframe.iloc[r[0]:r[1] + 1]
        trades.append((open_time, open_frame['Adj Close'], close_time,
                       close_frame['Adj Close'], r[2]))
        if r[2] < max_loss:
            max_loss_frame = frame
            max_loss = r[2]
        if r[2] < 0:
            loss_frames.append((r[5], r[3], r[4], r[2], frame))

    print(sum)
    return backtest
    pd.set_option('display.max_columns', 500)
    pd.set_option('display.width', 1000)

    with open("config.json", 'r') as f:
        data = json.load(f)

    test_env = False
    if test_env is False:
        params = data['prod']
    else:
        params = data['test']

    key = params['key']
    secret = params['secret']
    product = params['symbol']
    frequency = '1h'

    logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=logging.INFO, filemode='a',
                        filename='app.log')
    if test_env is True:
        endpoint = "https://testnet.bitmex.com/api/v1"
    else:
        endpoint = "https://www.bitmex.com/api/v1"

    client = RestClient(test_env, key, secret, product)
    websocket = MyWebSocket(endpoint, product, key, secret)
    websocket.connect_ws()
    symbol = BitMEXSymbol(product, client=client, frequency=frequency)
    dataframe = pd.DataFrame(symbol.fetch_data(datetime.utcnow() - timedelta(days=4), count=200))
    res_bro = run_resistance_breakout()
Exemple #7
0
        s.weighted = False
        s.rolling_period = 10
        s.min_profit = 13.5
        s.min_loss = -20
        s.setup()
        s.run()

        sum = 0
        for r in s.returns:
            sum += r[-1] - 13.5

    key = "VvD5-fMBfiZ9dlMtXP2pffHj"
    secret = "jROi3UZ5q_hkVW2RnK3xbCQEnTzpLXcnbOdUCJTnQFrrdUgj"
    product = 'XBTUSD'
    frequency = '5m'
    client = RestClient(False, key, secret, product)
    symbol = BitMEXSymbol(product, client=client, frequency=frequency)
    # now = datetime.utcnow()
    # data = []
    # fp = open('XBTUSD_5m_100days.txt', 'w')
    # wanted_ones = ['open', 'close', 'low', 'high', 'volume', 'timestamp']
    # for i in range(0, 100, 3):
    #     temp = symbol.fetch_data(datetime.utcnow() - timedelta(days=100 - i), count=864)
    #     ohlc = []
    #     for t in temp:
    #         d = {k: t[k] for k in wanted_ones}
    #         ohlc.append(str(d))
    #     sleep(2)
    #     fp.write('\n'.join(ohlc))
    #     fp.write('\n')
    # fp.close()