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)
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)
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, 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)
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")
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 Main(): resetOrdersPairs = False session = getSession('sqlite:///' + db_name) exchange = Binance(get_credentials_from_env=True) # Add all symbols on exchange # for symbol in exchange.SYMBOL_DATAS.keys(): # if exchange.SYMBOL_DATAS[symbol]["status"] == "TRADING" \ # and exchange.SYMBOL_DATAS[symbol]["quoteAsset"] == "BTC": # symbols.append(symbol) # First time you run this, uncomment the next line #initialize_database(session, symbols) bot = session.query(Bot).filter_by(name=bot_name).first() # strategy = AlwaysBuyStrategy() strategy = BBRSIStrategy(13, 40, 70, 30) bot_controller = BotController(session, bot, exchange, strategy) sp = yaspin() bot_controller.sp = sp bot_controller.sp_on = True while True: try: bot_controller.executeBot() except KeyboardInterrupt: return bot_controller.sp.start() left_to_sleep = time_to_sleep while left_to_sleep > 0: bot_controller.sp.text = "Waiting for {} more seconds...".format( left_to_sleep) time.sleep(1) left_to_sleep -= 1
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')])
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(): # 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)
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(get_credentials_from_env=True) strategy = AlwaysBuyStrategy() om = BotController(session, bot, exchange, strategy) while True: try: om.executeBot() except KeyboardInterrupt: return
def Main(): symbols = [] resetOrdersPairs = False session = getSession() exchange = Binance(get_credentials_from_env=True) Strategies = BotInitializer.getStrategies() bot = session.query(Bot).filter_by(name=bot_name).first() if bot is None: print('No bot found by name: ' + bot_name + '. Creating...') if bot_config['symbols'] is None: print('No symbols found in template. Adding all...') for symbol in exchange.SYMBOL_DATAS.keys(): if exchange.SYMBOL_DATAS[symbol]["status"] == "TRADING" \ and exchange.SYMBOL_DATAS[symbol]["quoteAsset"] == "BTC": symbols.append(symbol) InitializeDatabase(session, symbols, bot_name=bot_name) # Restart? Main() bot_config = BotInitializer.getYamlConfig(bot_name) if bot_config['symbols'] is not None: symbols = bot_config['strategy'] strategy = Strategies[bot_config['strategy']['name']](**bot_config['strategy']['params']) bot_controller = BotController(session, bot, exchange, strategy) sp = yaspin() bot_controller.sp = sp bot_controller.sp_on = True while True: try: bot_controller.executeBot() except KeyboardInterrupt: return bot_controller.sp.start() left_to_sleep = time_to_sleep while left_to_sleep > 0: bot_controller.sp.text = "Waiting for {} more seconds...".format(left_to_sleep) time.sleep(1) left_to_sleep -= 1
def Main(): resetOrdersPairs = False session = getSession('sqlite:///pyjuque_test_3.db') exchange = Binance() symbols = [] for symbol in exchange.SYMBOL_DATAS.keys(): if exchange.SYMBOL_DATAS[symbol]["status"] == "TRADING" \ and exchange.SYMBOL_DATAS[symbol]["quoteAsset"] == "BTC": symbols.append(symbol) # First time you run this, uncomment the next line # initialize_database(session, symbols) if resetOrdersPairs: clearOrdersFromDB(session) bot = session.query(Bot).filter_by(name='test_bot_2').first() # input your path to credentials here. # strategy = AlwaysBuyStrategy() strategy = BBRSIStrategy(13, 40, 70, 30) bot_controller = BotController(session, bot, exchange, strategy) sp = yaspin() bot_controller.sp = sp bot_controller.sp_on = True while True: try: bot_controller.executeBot() except KeyboardInterrupt: return bot_controller.sp.start() bot_controller.sp.text = "Waiting for {} seconds...".format( time_to_sleep) time.sleep(time_to_sleep)
def setUp(self): self.exchange = Binance() self.exchange.addCredentials("invalid_api_key", "invalid_secret_key")
import os import sys import time import json import datetime import websocket import threading from pprint import pprint from decimal import Decimal, Context from pyjuque.Exchanges.Binance import Binance ############## GLOBAL VARIABLES ############## ws = None # Websocket Object exchange = Binance( get_credentials_from_env=True) # The exchange order_book = dict(counter = 0) # The (per-symbol) order book order_book_lock = threading.Lock() # Order book threading lock order_book_initialized = dict() # Whether the (per-symbol) local # order book was initialized buffered_events = dict(counter = 0) # Buffers events before local # order book initialization ############## FOR COUNTING ############## buffered_events_count = 0 unbuffered_events_count = 0 def onOpen(ws): print('Opened connection') def onClose(ws): print('Closed connection')
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 entry and exit settings entrysets = EntrySettings( id=1, name='TimStoploss', initial_entry_allocation=0.01, signal_distance=0.2, # in % ) exitsets = ExitSettings( id=1, name='TimLoss', profit_target=1, # in % stop_loss_value=10, # in % exit_on_signal=False) bot.entry_settings = entrysets bot.exit_settings = exitsets # 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 = EMAXStrategy(5, 30) self.om = BotController(bot=self.bot, session=self.session, exchange=self.exchange, strategy=self.strategy)
dict(indicator_function=rsx_momentum_exhaustion, 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",
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 = OldOrderManagement(bot=self.bot, session=self.session, exchange=self.exchange, strategy=self.strategy)
dict(indicator_function=rsx_momentum_exhaustion, 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.getSymbolKlines(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",