def initialize(context): log.info('initializing arbitrage algorithm') # The context contains a new "exchanges" attribute which is a dictionary # of exchange objects by exchange name. This allow easy access to the # exchanges. context.buying_exchange = context.exchanges['poloniex'] context.selling_exchange = context.exchanges['bitfinex'] context.trading_pair_symbol = 'eth_btc' context.trading_pairs = dict() # Note the second parameter of the symbol() method # Passing the exchange name here returns a TradingPair object including # the exchange information. This allow all other operations using # the TradingPair to target the correct exchange. context.trading_pairs[context.buying_exchange] = \ symbol('eth_btc', context.buying_exchange.name) context.trading_pairs[context.selling_exchange] = \ symbol(context.trading_pair_symbol, context.selling_exchange.name) context.entry_points = [ dict(gap=0.03, amount=0.05), dict(gap=0.04, amount=0.1), dict(gap=0.05, amount=0.5), ] context.exit_points = [ dict(gap=-0.02, amount=0.5), ] context.SLIPPAGE_ALLOWED = 0.02 pass
def initialize(context): """ Initialise algorithm """ # set exchanges context.bitfinex = context.exchanges['bitfinex'] context.poloniex = context.exchanges['poloniex'] # set trading pairs context.bitfinex_trading_pair = symbol('btc_usdt', context.bitfinex.name) context.poloniex_trading_pair = symbol('btc_usdt', context.poloniex.name)
def load_pair(data, pair): sy = symbol(pair) startdate = symbol(pair).start_date enddate = symbol(pair).end_minute min_count = tdelta(startdate, enddate) c_data = data.history(sy, DATA_KEYS, min_count, '1T') print("{}: reading {} first: {} last: {} minutes: {}".format( datetime.now().strftime(t_f.DT_FORMAT), pair, startdate.strftime(t_f.DT_FORMAT), enddate.strftime(t_f.DT_FORMAT), min_count)) assert not c_data.empty, "{datetime.now().strftime(t_f.DT_FORMAT)}: empty dataframe from Catalyst" return c_data
def handle_data(context, data): context.github = get_dataset('github') context.github.sort_index(level=0, inplace=True) context.zec = data.history(symbol('zec_usdt'), ['price', ], bar_count=365, frequency="1d") context.xmr = data.history(symbol('xmr_usdt'), ['price', ], bar_count=365, frequency="1d")
def initialize(context): log.info('initializing pairs trading algorithm') context.bitfinex = context.exchanges['bitfinex'] context.pair1 = symbol('btc_usd', context.bitfinex.name) context.pair2 = symbol('xmr_usd', context.bitfinex.name) context.swallow_errors = True context.errors = [] context.threshold = 2.6 context.in_high = False context.in_low = False pass
def initialize(context): for attempt in context.attempts: context.attempts[attempt] = 100 context.trading_pairs = [ "btc_usdt", "eth_usdt", "ltc_usdt", "eos_usdt", "xrp_usdt", "iota_usdt", "bch_usdt", "trx_usdt", "xlm_usdt", "ada_usdt", ] context.trading_pairs = ["btc_usdt", "eth_usdt", "ltc_usdt"] context.allocation = 1 / len(context.trading_pairs) context.currently_trading = 0 atr_length = 28 atr_multiplier = 3 context.rsi_length = 14 dip_levels = 31.5 context.assets = [] context.day_timer = 1439 context.btc_trading_execution_time = 1440 context.trading_execution_time = 240 context.history_time = "4H" context.btc_history_time = "1D" context.btc_long = False context.first_run = True context.buy_all = BUY_ALL context.liquidate_all = LIQUIDATE_ALL if LIVE: error_handler.push_application() # Create BTC seperatly asset = CryptoAsset(symbol("btc_usdt"), dip_levels, 2, 12, context.allocation) context.assets.append(asset) for index, pair in enumerate(context.trading_pairs[1:]): asset = CryptoAsset(symbol(pair), dip_levels, atr_multiplier, atr_length, context.allocation) context.assets.append(asset)
def initialize(context): for attempt in context.attempts: context.attempts[attempt] = 100 context.trading_pairs = [ "btc_usdt", "eth_usdt", "ltc_usdt", "eos_usdt", "xrp_usdt", "iota_usdt", "bch_usdt", "trx_usdt", "xlm_usdt", "ada_usdt", ] context.allocation = 0.5 / 9 atr_length = 12 atr_multiplier = 2 context.rsi_length = 14 dip_levels = 31.5 context.assets = [] context.day_timer = 1441 context.btc_long = False context.trading_execution_time = 1440 context.history_time = "1D" context.buy_all = BUY_ALL context.liquidate_all = LIQUIDATE_ALL context.first_run = True if LIVE: error_handler.push_application() # context.exchanges['bitfinex'].get_balances() # Create BTC seperatly asset = CryptoAsset(symbol("btc_usdt"), dip_levels, atr_multiplier, atr_length, 0.5) context.assets.append(asset) for index, pair in enumerate(context.trading_pairs[1:]): asset = CryptoAsset( symbol(pair), dip_levels, atr_multiplier, atr_length, context.allocation ) context.assets.append(asset)
def update_ts(self, ts, context): self.catalyst_exchanges = [ context.exchanges[self.global_exchanges[i]] for i in range(self.global_leg_num) ] self.catalyst_assets = [ symbol(self.global_symbols[i], self.global_exchanges[i]) for i in range(self.global_leg_num) ] if not ts: return False if not self.ts or self.ts.date() != ts.date(): self.ts = ts eod = self.ts.date() file_prefix = self._generate_file_prefix(eod) self.storage_log_file = '{}.comics.log'.format(file_prefix) self.storage_trade_file = '{}.trade.csv'.format(file_prefix) self.storage_snapshot_file = '{}.snapshot.csv'.format(file_prefix) self.storage_plot_file = '{}.png'.format(file_prefix) logging.basicConfig( filename = os.path.join(self.storage_log_folder, self.storage_log_file),\ format = '%(asctime)s - %(levelname)s - %(message)s', level = self._get_log_level(self.storage_log_level) ) logging.info('[multileg_config] updated eod to {}'.format(eod)) if self.global_mode != 'live': set_commission(maker=self.sim_maker_fee_pct, taker=self.sim_taker_fee_pct) set_slippage(slippage=self.sim_slippage_pct) return True return False
def _init_func(self, context): """Sets up catalyst's context object and fetches external data""" self._context_ref = context self.state.load_from_context(context) self.log.info(f"Starting strategy on iteration {self.state.i}") self.state.asset = symbol(self.trading_info["ASSET"]) if self.is_backtest: self.log.debug("Setting benchmark") set_benchmark(self.state.asset) if self._datasets.items(): if self.state.DATA_FREQ == "daily": for dataset, manager in self._datasets.items(): manager.fetch_data() else: raise ValueError( 'Internal Error: Value of self.state.DATA_FREQ should be "minute" if you use Google Search Volume or Quandl datasets.' ) self._extra_init(context) if self.in_job and not self.is_backtest: job = get_current_job() if job.meta.get("PAUSED"): self.notify("Your strategy has resumed!") self.log.info(f"Resuming on trade iteration {self.state.i}") self._load_state_end_time(context) else: self.notify("Your strategy has started!") self.state.i = 0 self.state.errors = [] self.state.end = context.end for k, v in self.trading_info.items(): if "__" not in k: setattr(self.state, k, v) self.log.info("Initilized Strategy") self._check_configuration(context) # Set self.state.BARS size to work with custom minute frequency if self.state.DATA_FREQ == "minute": self.state.BARS = int( self.state.BARS * 24 * 60 / int(24 * 60 / int(self.state.MINUTE_FREQ)) ) self.date_init_reference = pd.Timestamp( "2013-01-01 00:00:00", tz="utc" ) + pd.Timedelta(minutes=int(self.state.MINUTE_TO_OPERATE)) # Set commissions context.set_commission( maker=self.state.MAKER_COMMISSION, taker=self.state.TAKER_COMMISSION ) self.state.dump_to_context(context)
def initialize(context): log.info('Starting TALib macd') context.ASSET_NAME = 'BTC_USD' context.asset = symbol(context.ASSET_NAME) context.ORDER_SIZE = 10 context.SLIPPAGE_ALLOWED = 0.05 context.errors = [] # Bars to look at per iteration should be bigger than SMA_SLOW context.BARS = 365 context.COUNT = 0 context.macds = pd.Series() context.macdSignals = pd.Series() context.macdHists = pd.Series() # Technical Analysis Settings context.MACD_FAST = 12 context.MACD_SLOW = 26 context.MACD_SIGNAL = 9 # 买卖点 context.BTC_BUY_TIME = [pd.Timestamp('2018-03-01 23:59:00',tz='UTC'), pd.Timestamp('2018-04-01 23:59:00',tz='UTC'), pd.Timestamp('2018-05-01 23:59:00',tz='UTC'), pd.Timestamp('2018-06-01 23:59:00',tz='UTC')] context.BTC_SELL_TIME = [pd.Timestamp('2018-07-01 23:59:00',tz='UTC'), pd.Timestamp('2018-08-01 23:59:00',tz='UTC'), pd.Timestamp('2018-09-01 23:59:00',tz='UTC'),pd.Timestamp('2018-10-01 23:59:00',tz='UTC')]
def initialize(context): context.i = 0 context.asset = symbol('btc_usdt') context.base_price = None context.signal = SIGNAL_INIT context.set_commission(maker=0.001, taker=0.001) context.set_slippage(slippage=0.001)
def initialize(context): log.info('Starting TALib Simple Example') context.ASSET_NAME = 'BTC_USDT' context.asset = symbol(context.ASSET_NAME) context.ORDER_SIZE = 10 context.SLIPPAGE_ALLOWED = 0.05 context.errors = [] # Bars to look at per iteration should be bigger than SMA_SLOW context.BARS = 365 context.COUNT = 0 # Technical Analysis Settings context.SMA_FAST = 50 context.SMA_SLOW = 100 context.RSI_PERIOD = 14 context.RSI_OVER_BOUGHT = 80 context.RSI_OVER_SOLD = 20 context.RSI_AVG_PERIOD = 15 context.MACD_FAST = 12 context.MACD_SLOW = 26 context.MACD_SIGNAL = 9 context.STOCH_K = 14 context.STOCH_D = 3 context.STOCH_OVER_BOUGHT = 80 context.STOCH_OVER_SOLD = 20 pass
def initialize(context): log.info('Starting TALib Simple Example') context.ASSET_NAME = 'BTC_USDT' context.asset = symbol(context.ASSET_NAME) context.ORDER_SIZE = 10 context.SLIPPAGE_ALLOWED = 0.05 context.swallow_errors = True context.errors = [] # Bars to look at per iteration should be bigger than SMA_SLOW context.BARS = 365 context.COUNT = 0 # Technical Analysis Settings context.SMA_FAST = 50 context.SMA_SLOW = 100 context.RSI_PERIOD = 14 context.RSI_OVER_BOUGHT = 80 context.RSI_OVER_SOLD = 20 context.RSI_AVG_PERIOD = 15 context.MACD_FAST = 12 context.MACD_SLOW = 26 context.MACD_SIGNAL = 9 context.STOCH_K = 14 context.STOCH_D = 3 context.STOCH_OVER_BOUGHT = 80 context.STOCH_OVER_SOLD = 20 pass
def initialize(context): log.info('Initializing Sure Fire Hedge Algorithm') context.bitfinex = context.exchanges['poloniex'] context.asset = symbol('btc_usdt', context.bitfinex.name) context.ORDER_SIZE = 0.1 context.BARS = 365 context.frequency = 'minute' context.swallow_errors = True context.errors = [] context.upper = 150 context.lower = 300 context.multiplyBy = 3 context.distance = 150 context.level = 1 context.SMA_FAST = 50 context.SMA_SLOW = 100 context.in_long = False context.in_short = False context.cost_basis = 1 pass
def __init__(self, market, strategy): super(Agent, self).__init__() self.logger.info("Initialized agent with {}".format( strategy.__class__.__name__)) self.market = symbol(market) self.strategy = strategy
def initialize(context): context.ASSET_NAME = 'USDT_ETH' context.asset = symbol(context.ASSET_NAME) # For all trading pairs in the poloniex bundle, the default denomination # currently supported by Catalyst is 1/1000th of a full coin. Use this # constant to scale the price of up to that of a full coin if desired. context.TICK_SIZE = 1.0
def initialize(context): context.i = 0 context.asset = symbol('btc_usd') context.base_price = None context.stop_price = 0 context.stop_pct = 0.99 context.trailing_stop_price = 0œ context.trailing_stop_pct = 0.98
def initialize(context): # Select asset of interest context.asset = symbol('BTC_USD') # set_commission(TradingPairFeeSchedule(maker_fee=0.5, taker_fee=0.5)) # set_slippage(TradingPairFixedSlippage(spread=0.5)) # Set up a rebalance method to run every day schedule_function(rebalance, date_rule=date_rules.every_day())
def initialize(context): context.A = symbol('xmr_usd') context.B = symbol('neo_usd') context.leverage = 1.0 # 1.0 - no leverage context.n_modelling = 72 # number of lookback bars for modelling context.tf = str( 60 ) + "T" # how many minutes in a timeframe; 1 - to get minute data (often errors happen); 60 - to get hourly data context.z_signal_in = st.norm.ppf( 1 - 0.0001 / 2) # z-score threshold to open an order context.z_signal_out = st.norm.ppf( 1 - 0.60 / 2) # z-score threshold to close an order context.min_spread = 0.035 # Threshold for minimal allowed spread context.set_commission(maker=0.001, taker=0.002) context.set_slippage(slippage=0.0005)
def initialize(context): # define asset context.asset = symbol("btc_usd") # amount of bars at specified timeframe context.i = 0 # beginning price context.base_price = None
def initialize(context): context.ASSET_NAME = global_vars.TARGET_ASSET if context.ASSET_NAME == "BCH_BTC": context.ASSET_NAME = "BCC_BTC" context.is_buying = True context.asset = symbol(context.ASSET_NAME) context.i = 0
def initialize(context): context.asset1 = symbol('btc_usd') context.asset2 = symbol('eth_usd') context.asset3 = symbol('xmr_usd') context.asset4 = symbol('xrp_usd') context.changes1Length = 2 context.changes2Length = 2 context.emaOfChanges1Length = 24 # The length of the change indicator. context.emaOfChanges2Length = 24 # The length of the change in change indicator. context.bar_count = 25 context.order_size = 1 context.slippage_allowed = 0.05 context._changes1Ratio = -1.0 context._changes2Ratio = 0.0 # The influence of change in change upon fitness. context._historyLength = 2 context._changes1Length = 2 context._changes2Length = 2
def initialize(context): # Portfolio assets list context.asset = symbol('btc_usd') # Bitcoin on Poloniex # Creates a .CSV file with the same name as this script to store results context.csvfile = open(FILE_NAME +'.csv', 'w+') context.csvwriter = csv.writer(context.csvfile) context.csvwriter.writerow(["Time", "price", "volume","high", "low","open","close"])
def initialize(context): context.ASSET_NAME = 'btc_usdt' context.TARGET_HODL_RATIO = 0.8 context.RESERVE_RATIO = 1.0 - context.TARGET_HODL_RATIO context.is_buying = True context.asset = symbol(context.ASSET_NAME) context.i = 0
def initialize(context): context.ASSET_NAME = 'btc_usd' context.TARGET_HODL_RATIO = 0.8 context.RESERVE_RATIO = 1.0 - context.TARGET_HODL_RATIO context.is_buying = True context.asset = symbol(context.ASSET_NAME) context.i = 0
def initialize(context): context.i = 0 context.asset = symbol('btc_usdt') context.base_price = None context.set_commission(maker=0.001, taker=0.001) context.set_slippage(slippage=0.001) context.last_prediction = 1000000 context.prediction = 0 context.num_hours = 0 context.train = pd.read_csv('../input/jan_june_btc_minute.csv')
def initialize(context): context.ASSET_NAME = 'ltc_usdt' context.asset = symbol(context.ASSET_NAME) context.i = -1 context.TARGET_HODL_RATIO = 0.8 context.startParabola = 0 #begin parabolic movement context.endParabola = 0 #end parabolic movement context.trackingState = 0 #0=nonparabolic ,
def _handle_data(context, data): global symbols if symbols is None: symbols = [symbol(c + '_usdt') for c in coins] print 'getting history for: %s' % [s.symbol for s in symbols] history = data.history( symbols, ['close', 'volume'], bar_count=1, # EXCEPTION, Change to 2 frequency='5T')
def initialize(context): """ 初始化 """ context.i = 0 # 经历过的交易周期 context.asset = symbol('bnb_usdt') # 交易对 context.base_price = None # 初始价格 context.signal = SIGNAL_INIT # 交易信号 context.set_commission(maker=0.001, taker=0.001) # 设置手续费 context.set_slippage(slippage=0.001) # 设置滑点
def handle_data_polo_partial_candles(context, data): history = data.history(symbol('btc_usdt'), ['volume'], bar_count=10, frequency='1D') print('\nnow: %s\n%s' % (data.current_dt, history)) if not hasattr(context, 'i'): context.i = 0 context.i += 1 if context.i > 5: raise Exception('stop')
def initialize(context): # This initialize function sets any data or variables that you'll use in # your algorithm. For instance, you'll want to define the trading pair (or # trading pairs) you want to backtest. You'll also want to define any # parameters or values you're going to use. # In our example, we're looking at Ether in USD Tether. context.eth_btc = symbol('etc_usdt') context.base_price = None context.current_day = None
def initialize(context): # Portfolio assets list context.asset = symbol(symbol_str) # Create an empty DataFrame to store results #context.pricing_data_1m = pd.DataFrame() #context.pricing_data_4h = pd.DataFrame() context.pricing_data_1h = pd.DataFrame() context.start_time = time.time()
def initialize(context): """ 初始化 """ log.info('策略初始化') context.i = 0 # 经历过的交易周期 # 设置加密货币池 context.asset_pool = [symbol('bnb_usdt')] context.set_commission(maker=0.001, taker=0.001) # 设置手续费 context.set_slippage(slippage=0.001) # 设置滑点
def initialize(context): log.info('initializing algo') context.ASSET_NAME = 'btc_usdt' context.asset = symbol(context.ASSET_NAME) context.TARGET_POSITIONS = 30 context.PROFIT_TARGET = 0.1 context.SLIPPAGE_ALLOWED = 0.02 context.errors = [] pass
def handle_data(context, data): prices = data.history( symbol('xlm_eth'), fields=['open', 'high', 'low', 'close'], bar_count=50, frequency='1T' ) set_print_settings() print(prices.tail(10)) context.data.append(prices) context.i = context.i + 1 if context.i == 3: context.interrupt_algorithm()
def default_initialize(context): # FIXME: set_benchmark # set_benchmark(symbol(context.parameters.COIN_PAIR)) context.coin_pair = symbol(context.parameters.COIN_PAIR) context.base_price = None context.current_day = None context.counter = -1 context.i = 0 context.candles_sample_rate = context.parameters.CANDLES_SAMPLE_RATE context.candles_frequency = context.parameters.CANDLES_FREQUENCY context.candles_buffer_size = context.parameters.CANDLES_BUFFER_SIZE context.set_commission( commission.PerShare(cost=context.parameters.COMMISSION_FEE))
def initialize(context): # This initialize function sets any data or variables that you'll use in # your algorithm. For instance, you'll want to define the trading pair (or # trading pairs) you want to backtest. You'll also want to define any # parameters or values you're going to use. # In our example, we're looking at Neo in Ether. context.market = symbol('eth_btc') context.base_price = None context.current_day = None context.RSI_OVERSOLD = 50 context.RSI_OVERBOUGHT = 60 context.CANDLE_SIZE = '5T' context.start_time = time.time() context.set_commission(maker=0.001, taker=0.002)
def initialize(context): log.info('initializing algo') context.asset = symbol('eth_btc') context.base_price = None context.MAX_HOLDINGS = 0.2 context.RSI_OVERSOLD = 30 context.RSI_OVERSOLD_BBANDS = 45 context.RSI_OVERBOUGHT_BBANDS = 55 context.SLIPPAGE_ALLOWED = 0.03 context.TARGET = 0.15 context.STOP_LOSS = 0.1 context.STOP = 0.03 context.position = None context.last_bar = None context.errors = [] pass
def initialize(context): context.asset = symbol('btc_usdt')
def initialize(context): context.assets = [symbol('eth_btc'), symbol('eth_usdt')]
def initialize(context): log.info('initializing') context.asset = symbol('eth_btc') context.base_price = None
def initialize(context): context.i = 0 context.asset = symbol('ltc_usd') context.base_price = None
def initialize(context): context.asset1 = symbol('fct_btc') context.asset2 = symbol('btc_usdt') context.coins = [context.asset1, context.asset2]
def initialize(context): print('initializing') context.asset = symbol('xcp_btc')
def initialize(context): context.asset = symbol('trx_btc')