Exemple #1
0
def Main():
    # Initialize exchanges and test
    symbol = "LTCUSDT"
    binance = Binance()
    sd = binance.SYMBOL_DATAS[symbol]
    df = binance.getOHLCV(symbol, "15m", limit=10000)

    def fitness_function(individual):
        pt = round(Decimal(int(individual[4])) / Decimal(1000), 3)
        entry_strategy.args = tuple(individual[0:4])
        exit_settings.pt = pt
        results = backtest(df, symbol, binance, entry_strategy, entry_settings,
                           exit_settings)
        return float(results['total_profit_loss'])

    optimiser = StrategyOptimiser(fitness_function=fitness_function,
                                  n_generations=30,
                                  generation_size=50,
                                  n_genes=5,
                                  gene_ranges=[(3, 40), (15, 80), (60, 100),
                                               (0, 40), (1004, 1150)],
                                  mutation_probability=0.3,
                                  gene_mutation_probability=0.5,
                                  n_select_best=15)

    best_children = optimiser.run_genetic_algo()
    pprint(best_children)
Exemple #2
0
def Main():
		exchange = Binance()
		symbol = "LTCUSDT"
		df = exchange.getOHLCV(symbol, "1h", 8000)

		start_time = df['time'][0]
		end_time = df['time'][len(df)-1]
		
		price_min = df['close'].min()
		price_max = df['close'].max()
		diff = price_max - price_min
		level1 = price_max - 0.236 * diff
		level2 = price_max - 0.382 * diff
		level3 = price_max - 0.618 * diff
		
		lines = []

		lines.append(horizontal_line(
			start_time, end_time, price_max, 
			color="rgba(255, 0, 0, 255)"))
		lines.append(horizontal_line(
			start_time, end_time, level1, 
			color="rgba(255, 255, 0, 255)"))
		lines.append(horizontal_line(
			start_time, end_time, level2, 
			color="rgba(0, 255, 0, 255)"))
		lines.append(horizontal_line(
			start_time, end_time, level3, 
			color="rgba(0, 255, 255, 255)"))
		lines.append(horizontal_line(
			start_time, end_time, price_min, 
			color="rgba(0, 0, 255, 255)"))

		PlotData(df, add_candles=False, plot_shapes=lines,
		plot_title="fib_levels", show_plot=True)
class BinanceTests(unittest.TestCase):

    ############################
    #### setup and teardown ####
    ############################

    # executed prior to each test
    def setUp(self):
        self.exchange = Binance()
        self.exchange.addCredentials("invalid_api_key", "invalid_secret_key")

    # executed after each test
    def tearDown(self):
        pass

    ###############
    #### tests ####
    ###############
    def test_AddCredentials(self):
        self.assertEqual(self.exchange.has_credentials, True,
                         "Exchange should have credentials now.")

    def test_GetAccountData(self):
        acct_data = self.exchange.getAccountData()
        assert isinstance(acct_data,
                          dict), "getAccountData should return a dict"
        assert acct_data.__contains__('code'), \
         "Response should contain an error since the api-secret key pair \
				is invalid."

    def test_GetTradingSymbols(self):
        trading_symbols = self.exchange.getTradingSymbols()
        assert isinstance(trading_symbols,
                          list), "getTradingSymbols should return a list"

    def test_GetSymbolKlines(self):

        limit = 1000
        timeframe = "1m"
        symbol = "BTCUSDT"

        df = self.exchange.getOHLCV(symbol, timeframe, limit)
        assert isinstance(
            df, DataFrame), "getSymbolKlines should return a dataframe"

        length = len(df) - 1
        assert length + 1 == limit, "there should be " + str(limit) \
         + " entries in the dataframe, not "+str(length + 1)

        for x in ['open', 'high', 'low', 'close', 'volume', 'time', 'date']:
            assert x in df.columns, \
             x+" should be a column in the Candlestick dataframe"

        for i in range(1, length):
            assert (df['close'][i] <= df['high'][i] and \
             df['close'][i] >= df['low'][i] and \
             df['open'][i] <= df['high'][i] and \
             df['open'][i] >= df['low'][i]), \
              "high should not be less than close nor open, and " \
              + "low should not be greater than either of them "
Exemple #4
0
def Main():
	exchange = Binance()
	symbol = 'BNBUSDT'
	df = exchange.getOHLCV(symbol, '1h', 500)
	strategy = OTTStrategy(1, 0.1)
	strategy.setUp(df)

	signals=[
		dict(points=strategy.getBuySignalsList(), name="buy_times"),
		dict(points=strategy.getSellSignalsList(), name="sell_times")]

	df['ott'] = df['ott'].shift(2)
	PlotData(df, plot_indicators=strategy.getIndicators(), signals=signals,
		show_plot=True, plot_title="OTTStrategy")
Exemple #5
0
def Main():
    # Initialize exchanges and test
    binance = Binance()

    # symbol = "ZILBTC"
    # symbol = "XRPBTC"
    symbol = "BTCUSDT"
    interval = "1m"
    df = binance.getOHLCV(symbol, interval, limit=1000)

    strategy = entry_strategy.strategy_class(*entry_strategy.args)
    strategy.setUp(df)
    # pprint(strategy.df)
    results = backtest(df, symbol, binance, entry_strategy, entry_settings,
                       exit_settings)

    print("P\L: {}".format(results["total_profit_loss"]))

    signals = [
        dict(points=results['buy_times'], name="buy_times"),
        dict(points=results['tp_sell_times'], name="tp_sell_times"),
        dict(points=results['sl_sell_times'], name="sl_sell_times"),
        dict(points=results['tsl_sell_times'], name="tsl_sell_times"),
        dict(points=results['tsl_active_times'], name="tsl_active_times"),
        dict(points=results['tsl_increase_times'], name="tsl_increase_times")
    ]

    plot_indicators = []
    for indicator in strategy.indicators:
        yaxis = 'y'
        if indicator['indicator_name'] == 'rsi':
            yaxis = 'y3'
        plot_indicators.append(
            dict(name=indicator['indicator_name'],
                 title=indicator['indicator_name'],
                 yaxis=yaxis))

    PlotData(
        df,
        add_candles=True,
        signals=signals,
        plot_indicators=plot_indicators,
        # plot_title=symbol,
        save_plot=True,
        plot_title="backtest_" + symbol.lower() + "_" + interval,
        show_plot=False
        # plot_shapes=lines,
    )
def Maine():
    exchange = Binance()
    symbol = 'BTCUSDT'
    df = exchange.getOHLCV(symbol, '1d')

    AddIndicator(df, 'sma', 'volma', 'volume', 10)
    signal = df.loc[df['volume'] > 2.4 * df['volma']]

    s_list = [
        dict(name='S/R',
             points=[(row['time'],
                      row['high']) if row['close'] > row['open'] else
                     (row['time'], row['low'])
                     for i, row in signal.iterrows()])
    ]

    HA(df, ['open', 'high', 'low', 'close'])

    ha_df = df
    ha_df['open'] = df['HA_open']
    ha_df['high'] = df['HA_high']
    ha_df['low'] = df['HA_low']
    ha_df['close'] = df['HA_close']

    lines = []
    last_time = df['time'][len(df) - 1]

    for s in s_list[0]['points']:
        line = go.layout.Shape(
            type="line",
            x0=s[0],
            y0=s[1],
            x1=last_time,
            y1=s[1],
        )
        lines.append(line)

    PlotData(
        ha_df,
        show_plot=True,
        signals=s_list,
        plot_shapes=lines,
        plot_indicators=[dict(name='volma', title="Volume MA", yaxis='y2')])
Exemple #7
0
def Main():
    # Initialize exchanges and test
    binance = Binance()
    symbol = "LTCBTC"
    df = binance.getOHLCV(symbol, "1m", limit=100000)

    strategy = entry_strategy.strategy_class(*entry_strategy.args)
    strategy.setUp(df)

    # pprint(strategy.df)
    results = backtest(df, symbol, binance, entry_strategy, entry_settings,
                       exit_settings)

    print("P\L: {}".format(results["total_profit_loss"]))

    signals = [
        dict(points=results['buy_times'], name="buy_times"),
        dict(points=results['tp_sell_times'], name="tp_sell_times"),
        dict(points=results['sl_sell_times'], name="sl_sell_times"),
        dict(points=results['tsl_sell_times'], name="tsl_sell_times"),
        dict(points=results['tsl_active_times'], name="tsl_active_times"),
        dict(points=results['tsl_increase_times'], name="tsl_increase_times")
    ]

    plot_indicators = []
    for indicator in strategy.indicators:
        yaxis = 'y'
        if indicator['indicator_name'] == 'rsi':
            yaxis = 'y3'
        plot_indicators.append(
            dict(name=indicator['indicator_name'],
                 title=indicator['indicator_name'],
                 yaxis=yaxis))

    PlotData(df,
             signals=signals,
             plot_indicators=plot_indicators,
             save_plot=True,
             show_plot=True)
                 col_name=['rsx', 'rsx_me_ob', 'rsx_me_os'],
                 mfi_length=self.mfi_length,
                 ob_level=self.ob_level,
                 os_level=self.os_level),
        ]

    def checkLongSignal(self, i):
        return self.df['rsx_me_os'][i]

    def checkShortSignal(self, i):
        return self.df['rsx_me_ob'][i]


if __name__ == '__main__':
    exchange = Binance()
    df = exchange.getOHLCV(symbol="ETHUSDT", interval="5m", limit=4000)

    strategy = CustomIndicatorStrategy()
    strategy.setUp(df)

    length = len(df['close'])
    longs = [(strategy.df['time'][i], strategy.df['close'][i])
             for i in range(length) if strategy.checkLongSignal(i)]

    shorts = [(strategy.df['time'][i], strategy.df['close'][i])
              for i in range(length) if strategy.checkShortSignal(i)]

    # These are for plotting
    plotting_indicators = [
        dict(name="rsx",
             title="RSX",