def handle_data(context, data): current_time = get_datetime().time() # When model is empty if len(context.model.get_renko_prices()) == 0: context.model = pyrenko.renko() history = data.history(context.asset, 'price', bar_count=context.n_history, frequency=context.tf) # Get daily absolute returns diffs = history.diff(context.diff_lag).abs() diffs = diffs[~np.isnan(diffs)] # Calculate IQR of daily returns iqr_diffs = np.percentile(diffs, [25, 75]) # Find the optimal brick size opt_bs = opt.fminbound(lambda x: -evaluate_renko( brick=x, history=history, column_name='score'), iqr_diffs[0], iqr_diffs[1], disp=0) # Build the model context.last_brick_size = opt_bs context.model.set_brick_size(brick_size=opt_bs, auto=False) context.model.build_history(prices=history) # Open a position order_target_percent( context.asset, context.leverage * context.model.get_renko_directions()[-1]) else: last_price = data.history( context.asset, 'price', bar_count=1, frequency='1440T', ) # Just for output and debug prev = context.model.get_renko_prices()[-1] prev_dir = context.model.get_renko_directions()[-1] num_created_bars = context.model.do_next(last_price) # If the last price moves in the backward direction we should rebuild the model if np.sign(context.portfolio.positions[context.asset].amount * context.model.get_renko_directions()[-1]) == -1: order_target_percent(context.asset, 0.0) context.model = pyrenko.renko() # or we cover the part of the position elif context.part_cover_ratio > 0.0 and num_created_bars != 0: order_target( context.asset, context.portfolio.positions[context.asset].amount * (1.0 - context.part_cover_ratio))
def initialize(context): context.asset = symbol('eth_btc') context.leverage = 1.0 # 1.0 - no leverage context.n_history = 24 * 15 # Number of lookback bars for modelling context.tf = '60T' # How many minutes in a timeframe context.model = pyrenko.renko() # Renko object context.part_cover_ratio = 0.166 # Partially cover position ratio context.last_brick_size = 0.0 # Last optimal brick size (just for storing) context.set_benchmark(context.asset) context.set_commission(maker = 0.001, taker = 0.002) context.set_slippage(slippage = 0.0005)
def initialize(context): context.asset = symbol('eth_btc') context.leverage = 1.0 # 1.0 - no leverage context.n_history = int( params['n_history']) # Number of lookback bars for modelling context.tf = str(int( params['tf'])) + 'T' # How many minutes in a timeframe context.diff_lag = int( params['diff_lag']) # Lag of differences to get returns context.model = pyrenko.renko() # Renko object context.part_cover_ratio = float( params['part_cover_ratio']) # Partially cover position ratio context.last_brick_size = 0.0 # Last optimal brick size (just for storing) context.set_benchmark(context.asset) context.set_commission(maker=0.001, taker=0.002) context.set_slippage(slippage=0.0005)
def initialize(context): context.i = 0 context.asset = symbol('btc_usdt') context.tf = '1H' context.atr_time = 51 context.bb = 8 context.model = pyrenko.renko() context.close_trigger = [1, -1, -1] context.open_trigger = [-1, 1, 1] context.is_open = False context.num_trades = 0 context.set_commission(maker=0.001, taker=0.002) context.set_slippage(slippage=0.001) context.order_price = None context.order_result = [] context.close_price = None context.started = None context.finished = None context.amount = None context.closed_by = None
def evaluate_renko(brick, history, column_name): renko_obj = pyrenko.renko() renko_obj.set_brick_size(brick_size=brick, auto=False) renko_obj.build_history(prices=history) return renko_obj.evaluate()[column_name]
return renko_obj.evaluate()[column_name] # Get ATR values (it needs to get boundaries) # Drop NaNs atr = talib.ATR(high=np.double(close_prices.iloc[:, 2]), low=np.double(close_prices.iloc[:, 3]), close=np.double(close_prices.iloc[:, 4]), timeperiod=14) atr = atr[np.isnan(atr) == False] # Get optimal brick size as maximum of score function by Brent's (or similar) method # First and Last ATR values are used as the boundaries optimal_brick_sfo = opt.fminbound(lambda x: -evaluate_renko( brick=x, history=close_prices.iloc[:, 4], column_name='score'), np.min(atr), np.max(atr), disp=0) renko_obj = pyrenko.renko() print('Set brick size (manual mode): ', renko_obj.set_brick_size(auto=False, brick_size=optimal_brick_sfo)) renko_obj.build_history(prices=close_prices.iloc[:, 4]) print('Renko bar prices: ', renko_obj.get_renko_prices()) print('Renko bar directions: ', renko_obj.get_renko_directions()) print('Renko bar evaluation: ', renko_obj.evaluate()) print('Balance: ', renko_obj.get_balance()) if len(renko_obj.get_renko_prices()) > 1: renko_obj.plot_renko()
sta.append('../' + datetime.datetime.strftime(time - datetime.timedelta( days=i), "%Y%m%d") + '.csv') print('starting to load csv backtest data... days: ' + str(args.days)) #data = pd.DataFrame(helper.load_dfs_mult('XBTUSD', files=sta, location='../')) # uses multiprocessing to parse huge csv datafiles data = get_data( sta ) # get_data is a generator that returns a pandas dataframe for 5 day chunks of data print('finished loading csv backtest data... starting renko brick calculation') renko_obj = pyrenko.renko(plot=False, j_backtest=True, fast=int(args.fast[0]), slow=int(args.fast[1]), signal_l=int(args.fast[2]), to_trade=args.trade, strategy=args.tr, ordtype=args.order_type) renko_obj.set_brick_size(brick_size=args.brick_size, auto=False) # sets brick_size hyperparam in dollars while True: try: renko_obj.build_history(prices=next(data), timestamps=['']) # builds renko backtest except Exception as e: print(e) break trades = renko_obj.plot_renko() # starts live renko brick calculation # 2019-12-17D23:09:17.575367000 # sample timestamp from bitmex
def handle_data(context, data): current_time = get_datetime().time() if current_time.hour == 0 and current_time.minute == 0: print('Current date is ' + str(get_datetime().date())) # When model is empty if len(context.model.get_renko_prices()) == 0: context.model = pyrenko.renko() history = data.history(context.asset, 'price', bar_count = context.n_history, frequency = context.tf ) # Get daily absolute returns diffs = history.diff(24).abs() diffs = diffs[~np.isnan(diffs)] # Calculate IQR of daily returns iqr_diffs = np.percentile(diffs, [25, 75]) # Find the optimal brick size opt_bs = opt.fminbound(lambda x: -evaluate_renko(brick = x, history = history, column_name = 'score'), iqr_diffs[0], iqr_diffs[1], disp=0) # Build the model print('REBUILDING RENKO: ' + str(opt_bs)) context.last_brick_size = opt_bs context.model.set_brick_size(brick_size = opt_bs, auto = False) context.model.build_history(prices = history) # Open a position order_target_percent(context.asset, context.leverage * context.model.get_renko_directions()[-1]) # Store some information record( rebuilding_status = 1, brick_size = context.last_brick_size, price = history[-1], renko_price = context.model.get_renko_prices()[-1], num_created_bars = 0, amount = context.portfolio.positions[context.asset].amount ) else: last_price = data.history(context.asset, 'price', bar_count = 1, frequency = '1440T', ) # Just for output and debug prev = context.model.get_renko_prices()[-1] prev_dir = context.model.get_renko_directions()[-1] num_created_bars = context.model.do_next(last_price) if num_created_bars != 0: print('New Renko bars created') print('last price: ' + str(last_price)) print('previous Renko price: ' + str(prev)) print('current Renko price: ' + str(context.model.get_renko_prices()[-1])) print('direction: ' + str(prev_dir)) print('brick size: ' + str(context.model.brick_size)) # Store some information record( rebuilding_status = 0, brick_size = context.last_brick_size, price = last_price, renko_price = context.model.get_renko_prices()[-1], num_created_bars = num_created_bars, amount = context.portfolio.positions[context.asset].amount ) # If the last price moves in the backward direction we should rebuild the model if np.sign(context.portfolio.positions[context.asset].amount * context.model.get_renko_directions()[-1]) == -1: order_target_percent(context.asset, 0.0) context.model = pyrenko.renko() # or we cover the part of the position elif context.part_cover_ratio > 0.0 and num_created_bars != 0: order_target(context.asset, context.portfolio.positions[context.asset].amount * (1.0 - context.part_cover_ratio))
def get_tickers(): size = 5 if interval is not None: size = int(interval) maxdict = 5 Iq.start_candles_stream(asset, size, maxdict) time.sleep(1) candles = Iq.get_realtime_candles(asset, size) global ticks for candle in candles: cand = candles[candle] cd_handle = {} if "open" in cand: cd_handle['open'] = cand["open"] cd_handle['high'] = cand["max"] cd_handle['low'] = cand["min"] cd_handle['close'] = cand["close"] cd_handle['created_at'] = dt.datetime.fromtimestamp( cand["from"]).isoformat() cd_handle['timestamp'] = cand["from"] cd_handle['volume'] = cand["volume"] ticks.append(cd_handle) # for i in range(2): # candles=[] # candles=Iq.get_candles(asset, int(interval), 1000, time.time()) # cds = [] # for candle in candles: # cd_handle = {} # if candle["open"]: # cd_handle['open'] = candle["open"] # cd_handle['high'] = candle["max"] # cd_handle['low'] = candle["min"] # cd_handle['close'] = candle["close"] # cd_handle['created_at'] = dt.datetime.fromtimestamp(candle["from"]).isoformat() # cd_handle['timestamp'] = candle["from"] # cd_handle['volume'] = candle["volume"] # cds.append(cd_handle) # ticks = cds + ticks # end_from_time = int(cds[0]["timestamp"]) - 1 try: renko_obj_atr.reset_data() df = pd.DataFrame(ticks[-dim:]) # Get optimal brick size based optimal_brick = pyrenko.renko().set_brick_size( auto=True, HLC_history=df[["high", "low", "close"]]) renko_obj_atr.set_brick_size(auto=False, brick_size=optimal_brick) renko_obj_atr.build_history(prices=df.close) renko_obj_atr.get_renko_prices() renko_obj_atr.get_renko_directions() renko_obj_atr.evaluate() if len(renko_obj_atr.get_renko_prices()) > 1: renko_obj_atr.set_chart_title(asset) renko_obj_atr.plot_renko() except IOError: print("I/O error")
required=False, help="Pass sufix to file ", metavar="SUFIX") args = parser.parse_args() asset = args.asset or "USDJPY" interval = args.interval or 60 sufix = args.filesufix or "" ## AUTH user = userdata.mainUser Iq = IQ_Option(user["username"], user["password"]) # Build Renko chart renko_obj_atr = pyrenko.renko() fig, ax = plt.subplots(1, figsize=(20, 10)) renko_obj_atr.set_ax(ax) renko_obj_atr.set_ema_period(45) dim = 1600 # tamanho da janela ticks = [] # fileName= 'data/' + asset + '-renko.csv' # isThereFile = os.path.isfile(fileName) # if isThereFile: # pass # else: # record = open(fileName,"w") # record.write("open,high,low, close, created_at, timestamp, volume\n")
cd_handle['high'] = candle["max"] cd_handle['low'] = candle["min"] cd_handle['close'] = candle["close"] cd_handle['created_at'] = dt.datetime.fromtimestamp( candle["from"]).isoformat() cd_handle['timestamp'] = candle["from"] cd_handle['volume'] = candle["volume"] cds.append(cd_handle) ticks = cds + ticks end_from_time = int(cds[0]["timestamp"]) - 1 try: df = pd.DataFrame(ticks) # Get optimal brick size based optimal_brick = pyrenko.renko().set_brick_size( auto=True, HLC_history=df[["high", "low", "close"]]) # Build Renko chart renko_obj_atr = pyrenko.renko() renko_obj_atr.set_brick_size(auto=False, brick_size=optimal_brick) renko_obj_atr.build_history(prices=df.close) print('Renko bar prices: ', renko_obj_atr.get_renko_prices()) print('Renko bar directions: ', renko_obj_atr.get_renko_directions()) print('Renko bar evaluation: ', renko_obj_atr.evaluate()) if len(renko_obj_atr.get_renko_prices()) > 1: renko_obj_atr.set_chart_title(asset) renko_obj_atr.plot_renko() except IOError: print("I/O error")
def handle_data(context, data): current_time = get_datetime().time() if current_time.hour == 0 and current_time.minute == 0: print('Current date is ' + str(get_datetime().date())) context.i += 1 if context.i < context.atr_time: return if not data.can_trade(context.asset): return starting_cash = context.portfolio.starting_cash current = data.current(context.asset, 'close') price = data.current(context.asset, 'price') last_price = data.history(context.asset, 'price', bar_count=context.atr_time - 1, frequency=context.tf) if order_vol == 0.1 and stop == 0.9975: if context.i % 60 == 0: ohlcv_data = data.history( context.asset, fields=['open', 'high', 'low', 'close', 'volume'], bar_count=1, frequency='H') get_ohlcv(database=db, exchange=exchange_name, pair='BTCUSDT', open=ohlcv_data.open, high=ohlcv_data.high, low=ohlcv_data.low, close=ohlcv_data.close, volume=ohlcv_data.volume, timestamp=datetime.timestamp(get_datetime())) bb_data = data.history(context.asset, 'close', bar_count=context.bb, frequency=context.tf) hlc_data = data.history(context.asset, fields=['high', 'low', 'close'], bar_count=context.atr_time, frequency=context.tf) upperband, middleband, lowerband = talib.BBANDS(bb_data, timeperiod=context.bb - 1, nbdevup=2, nbdevdn=2, matype=0) upperband, middleband, lowerband = upperband[-1], middleband[ -1], lowerband[-1] bb_range = upperband - lowerband record(price=price, starting_cash=starting_cash, cash=context.portfolio.cash, upperband=upperband, middleband=middleband, lowerband=lowerband, num_trades=context.num_trades, order_result=context.order_result) context.model = pyrenko.renko() optimal_brick = context.model.set_brick_size(HLC_history=hlc_data) context.model.build_history(prices=last_price) prev_dir = context.model.get_renko_directions() last_dir = prev_dir[-4:-1] if not context.is_open: if last_dir == context.open_trigger and bb_range > 500: order_target_percent(context.asset, order_vol, limit_price=current * 1.001) context.is_open = True context.started = get_open_orders(context.asset)[-1].dt context.order_price = get_open_orders(context.asset)[-1].limit context.amount = get_open_orders(context.asset)[-1].amount positions(db, type=algo_type, side='Buy', start=context.started, open_price=context.order_price, finish=None, close=None, amount=context.amount, status='Open', closed_by=None, exchange=exchange_name, timestamp=datetime.timestamp(get_datetime())) else: if current <= context.order_price * stop and stop != 0: close_id = order_target_percent(context.asset, 0, limit_price=current) context.is_open = False context.num_trades += 1 price_diff = current - context.order_price context.order_result.append(price_diff) context.finished = get_order(close_id).dt context.close_price = get_order(close_id).limit context.closed_by = 'Stop Loss' record(num_trades=context.num_trades, order_result=context.order_result) query = Position.select(fn.MAX(Position.id)) p = (Position.update({ 'finished': context.finished, 'closed_price': context.close_price, 'closed_by': context.closed_by, 'status': 'Closed' }).where(Position.id == query.scalar())) p.execute() else: if last_dir == context.close_trigger: close_id = order_target_percent(context.asset, 0, limit_price=current) context.model = pyrenko.renko() context.is_open = False price_diff = current - context.order_price context.order_result.append(price_diff) context.num_trades += 1 context.finished = get_order(close_id).dt context.close_price = get_order(close_id).limit context.closed_by = 'Algo' record(num_trades=context.num_trades, order_result=context.order_result) query = Position.select(fn.MAX(Position.id)) p = (Position.update({ 'finished': context.finished, 'closed_price': context.close_price, 'closed_by': context.closed_by, 'status': 'Closed' }).where(Position.id == query.scalar())) p.execute(db)