def Main(): # Initialize exchanges and test binance = Binance() symbol = "ADABNB" symbols = binance.getTradingSymbols(['BNB']) for symbol in symbols: sd = binance.SYMBOL_DATAS[symbol] df = binance.getSymbolKlines(symbol, "15m", limit=1000) individual = [8, 24, 84, 18, 1024] def fitness_function(individual): pt = round(Decimal(int(individual[4])) / Decimal(1000), 3) entry_strategy.args = tuple(individual[0:4]) exit_settings.pt = pt return backtest(df, sd, binance, entry_strategy, entry_settings, exit_settings) results = fitness_function(individual) pprint(results['total_profit_loss']) strategy = entry_strategy.strategy_class(*entry_strategy.args) strategy.setup(df) 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") ]
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.getSymbolKlines(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 "
def Main(): # Initialize exchanges and test symbol = "LTCUSDT" binance = Binance() sd = binance.SYMBOL_DATAS[symbol] df = binance.getSymbolKlines(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, sd, 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)
def Main(): # Initialize exchanges and test binance = Binance() symbol = "LTCUSDT" df = binance.getSymbolKlines(symbol, "5m", limit=1000) results = backtest(df, symbol, binance, entry_strategy, entry_settings, exit_settings) pprint(results) strategy = entry_strategy.strategy_class(*entry_strategy.args) 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: plot_indicators.append( dict(name=indicator['indicator_name'], title=indicator['indicator_name'])) PlotData(df, signals=signals, plot_indicators=plot_indicators, save_plot=True, show_plot=True)
def Main(): # Initialize exchanges and test binance = Binance() symbol = "LTCUSDT" sd = binance.SYMBOL_DATAS[symbol] df = binance.getSymbolKlines(symbol, "5m", limit=3000) results = backtest(df, sd, binance, entry_strategy, entry_settings, exit_settings) # pprint(results) strategy = entry_strategy.strategy_class(df, *entry_strategy.args) 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") ] PlotData(df, signals=signals, plot_indicators=strategy.getIndicators(), save_plot=True, show_plot=True)
def try_entry_order(bot: Bot, symbol: str, strategy_function: BBRSIStrategy): """ """ binance = Binance() df = binance.getSymbolKlines(symbol, "5m", limit=100) strat = BBRSIStrategy(df, 8, 100, 60, 40) l = len(df) - 1 buy_signal = strat.checkBuySignal(l) if buy: take_profit = bot.profit_target desired_price = df['close'][l] quote_qty = Decimal(bot.starting_balance) * Decimal( bot.trade_allocation) / Decimal(100) desired_quantity = quote_qty / desired_price order = Order(bot_id=bot.id, symbol=symbol, status="NEW", side="BUY", is_entry=True, entry_price=desired_price, original_quantity=desired_quantity, executed_quantity=0, is_closed=False, is_test=bot.test_run) db.session.add(order) db.session.commit() order_response = dict() if bot.test_run: order_response = exchange.placeLimitOrder(symbol=symbol, price=desired_price, side="BUY", test=True, amount=desired_quantity, custom_id=order.id) else: order_response = exchange.placeLimitOrder(symbol=symbol, price=desired_price, side="BUY", amount=desired_quantity, custom_id=order.id) if exchange.isValidResponse(order_response): bot.current_balance = bot.current_balance - quote_qty exchange.updateSQLOrderModel(order, order_response) pair = bot.getPairOfSymbol(symbol) pair.current_order_id = order.id pair.active = False db.session.commit() else: db.session.query(Order).filter(Order.id == order.id).delete() db.session.commit()
def Main(): exchange = Binance() symbol = "LTCUSDT" df = exchange.getSymbolKlines(symbol, "1h", 5000) 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)
def Main(): exchange = Binance() symbol = 'BNBUSDT' df = exchange.getSymbolKlines(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")
def Maine(): exchange = Binance() symbol = 'BTCUSDT' df = exchange.getSymbolKlines(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')])
def Main(): symbol = "LTCUSDT" print("Init binance...") binance = Binance() print("Getting data from binance...") df = binance.getSymbolKlines(symbol, "15m", limit=10000) print("Calculating Supertrend...") supertrend_df = ST(df, 10, 3) supertrend_df_longer = ST(df, 30, 9) lower_supertrend = supertrend_df.where( supertrend_df['supertrend'] < supertrend_df['close']) upper_supertrend = supertrend_df.where( supertrend_df['supertrend'] > supertrend_df['close']) lower_supertrend_longer = supertrend_df_longer.where( supertrend_df_longer['supertrend'] < supertrend_df_longer['close']) upper_supertrend_longer = supertrend_df_longer.where( supertrend_df_longer['supertrend'] > supertrend_df_longer['close']) df['lower_supertrend'] = lower_supertrend['supertrend'] df['upper_supertrend'] = upper_supertrend['supertrend'] df['lower_supertrend_longer'] = lower_supertrend_longer['supertrend'] df['upper_supertrend_longer'] = upper_supertrend_longer['supertrend'] print("Plotting...") PlotData(df, plot_indicators=[ dict(name='lower_supertrend', title="Lower ST", color='green'), dict(name='upper_supertrend', title="Upper ST", color='red'), dict(name='lower_supertrend_longer', title="Lower ST Longer", color='green'), dict(name='upper_supertrend_longer', title="Upper ST Longer", color='red') ], show_plot=True)
def Main(): resetOrdersPairs = False session = get_session('sqlite:///pyjuquetest1.db') # First time you run this, uncomment the next line initialize_database(session) if resetOrdersPairs: clearOrdersFromDB(session) bot = session.query(Bot).filter_by(name='test_bot_2').first() # input your path to credentials here. exchange = Binance(filename=) strategy = AlwaysBuyStrategy() om = BotController(session, bot, exchange, strategy) while True: try: om.executeBot() except KeyboardInterrupt: return
def Main(): """ """ session = get_session('sqlite:///app.db') # First time you run this, uncomment the next line # initialize_database(session) bot = session.query(Bot).filter_by(name='test_bot_1').first() exchange = Binance() manager = OrderManagement(session=session, bot=bot, exchange=exchange, strategy=BBRSIStrategy(8, 100, 60, 40)) while True: try: manager.execute_bot() time.sleep(10) except KeyboardInterrupt: return
def setUp(self): self.exchange = Binance() self.df_BTCUSD_1k = pd.read_csv('./tests/data/BTCUSD_1m_1k.csv') self.df_BTCUSD_10k = pd.read_csv('./tests/data/BTCUSD_1m_10k.csv') self.df_ADABTC_1k = pd.read_csv('./tests/data/ADABTC_1m_1k.csv') # define bot params self.bot_name = 'ada_test_bot' self.bot_id = 1 self.starting_balance = 2 self.current_balance = 3 self.profit_target = 4 self.test_run = True self.quote_asset = 'BTC' # define pair params self.pair_id_ada = 2 self.symbol_ada = 'ADABTC' self.profit_loss_ada = 5 self.pair_id_eth = 3 self.symbol_eth = 'ETHBTC' self.profit_loss_eth = 6 # define order params self.order_1_id = 1 self.order_2_id = 2 self.order_symbol = self.symbol_eth self.entry_price = 2 self.original_quantity = 3 self.executed_quantity = 4 self.status = 'NEW' self.is_closed = True self.side = 'BUY' self.is_test = True self.session = get_session() self.assertEqual(len(self.session.query(Bot).all()), 0) # Create bot bot = Bot( id=self.bot_id, name=self.bot_name, quote_asset=self.quote_asset, starting_balance=self.starting_balance, current_balance=self.current_balance, profit_target=self.profit_target, test_run=self.test_run, ) # Create ETHBTC pair ethpair = Pair( id=self.pair_id_eth, bot_id=self.bot_id, symbol=self.symbol_eth, profit_loss=self.profit_loss_eth, ) # Create ADABTC pair adapair = Pair( id=self.pair_id_ada, bot_id=self.bot_id, symbol=self.symbol_ada, profit_loss=self.profit_loss_ada, ) # Create ethereum buy order eth_order = Order( id=self.order_1_id, bot_id=self.bot_id, symbol=self.order_symbol, entry_price=self.entry_price, original_quantity=self.original_quantity, executed_quantity=self.executed_quantity, status=self.status, side=self.side, is_test=self.is_test, ) eth_order_closed = Order( id=self.order_2_id, bot_id=self.bot_id, symbol=self.order_symbol, entry_price=self.entry_price, original_quantity=self.original_quantity, executed_quantity=self.executed_quantity, is_closed=self.is_closed, status=self.status, side=self.side, is_test=self.is_test, ) self.session.add(bot) self.session.add(adapair) self.session.add(ethpair) self.session.add(eth_order) self.session.add(eth_order_closed) self.session.commit() self.bot = self.session.query(Bot).filter_by( name=self.bot_name).first() self.strategy = EMACrossover(5, 30) self.om = OrderManagement(bot=self.bot, session=self.session, exchange=self.exchange, strategy=self.strategy)
def setUp(self): self.exchange = Binance() self.exchange.addCredentials("invalid_api_key", "invalid_secret_key")
from time import time def timeit(function, text=None, *args): ''' Used to print the time it takes to run a certain function. ''' start = time() ret = function(*args) end = time() if text is not False: if text is None or text == "": text = function.__name__ + " took " print(text + str(round(end - start, 4)) + " s") return ret, end - start import os import sys curr_path = os.path.abspath(__file__) root_path = os.path.abspath( os.path.join(curr_path, os.path.pardir, os.path.pardir)) sys.path.append(root_path) from bot.Exchanges.Binance import Binance exchange = Binance() df = exchange.getSymbolKlines("BTCUSDT", "1m", 1000) df.to_csv('tests/data/BTCUSD_1m_1k.csv')
def try_exit_order(bot: Bot, order): """ """ symbol = order.symbol exchange = Binance() pair: Pair = bot.getPairOfSymbol(symbol) order: Order = Order.query.get(order.id) if order.is_test: df = exchange.getSymbolKlines(order.symbol, '5m', 50) l = len(df) - 1 filled = False for index, row in df.iterrows(): if datetime.fromtimestamp(row['time'] / 1000) > order.timestamp: if order.is_entry: if row['low'] < order.entry_price: order.status = exchange.ORDER_STATUS_FILLED order.executed_quantity = order.original_quantity order.is_closed = True filled = True db.session.commit() break elif not order.is_entry: if row['high'] > Decimal(order.entry_price): order.status = exchange.ORDER_STATUS_FILLED order.executed_quantity = order.original_quantity order.is_closed = True filled = True db.session.commit() break else: exchange_order_info = exchange.getOrderInfo(symbol, order.id) if not exchange.isValidResponse(exchange_order_info): return order.status = exchange_order_info['status'] order.executed_quantity = exchange_order_info['executedQty'] db.session.commit() if order.status == exchange.ORDER_STATUS_FILLED: if order.is_entry: # If this entry order has been filled new_order_model = Order(bot_id=bot.id, symbol=symbol, status="NEW", side="SELL", is_entry=False, entry_price=order.take_profit_price, original_quantity=order.executed_quantity, executed_quantity=0, is_closed=False, is_test=bot.test_run) db.session.add(new_order_model) db.session.commit() exit_price = order.take_profit_price new_order_response = dict(message="success") if bot.test_run: new_order_response = exchange.placeLimitOrder( symbol=symbol, price=exit_price, side="SELL", amount=order.executed_quantity, test=bot.test_run, custom_id=new_order_model.id) else: new_order_response = exchange.placeLimitOrder( symbol=symbol, price=exit_price, side="SELL", amount=order.executed_quantity, custom_id=new_order_model.id) if exchange.isValidResponse(new_order_response): exchange.updateSQLOrderModel(new_order_model, new_order_response, bot) new_order_model.matched_order_id = order.id order.is_closed = True order.matched_order_id = new_order_model.id pair.active = False pair.current_order_id = new_order_model.id db.session.commit() else: db.session.query(Order).filter( Order.id == new_order_model.id).delete() db.session.commit() else: order.is_closed = True pair.active = True pair.current_order_id = None db.session.commit() # If the order has been cancelled, set the order to close and start from beginning elif order.status == exchange.ORDER_STATUS_CANCELED: order.is_closed = True pair.active = True pair.current_order_id = None db.session.commit()