コード例 #1
0
class EMAStrategy(Strategy):
    indicators = {'emaL': EMA([100]), 'emaS': EMA([20])}

    def onEnter(self, update):
        iv = self.indicatorValues()
        emaS = self.indicators['emaS']
        s = iv['emaS']
        l = iv['emaL']

        if emaS.crossed(l):
            if s > l:
                return self.openLongPositionMarket({
                    'mtsCreate': update['mts'],
                    'price': update['price'],
                    'amount': 1,
                })
            else:
                return self.openShortPositionMarket({
                    'mtsCreate': update['mts'],
                    'price': update['price'],
                    'amount': 1,
                })

    def onUpdateShort(self, update):
        iv = self.indicatorValues()
        s = iv['emaS']
        l = iv['emaL']

        if s < l:
            return self.closePositionMarket({
                'mtsCreate': update['mts'],
                'price': update['price']
            })

    def onUpdateLong(self, update):
        iv = self.indicatorValues()
        s = iv['emaS']
        l = iv['emaL']

        if s > l:
            return self.closePositionMarket({
                'mtsCreate': update['mts'],
                'price': update['price']
            })
コード例 #2
0
import sys
import asyncio
sys.path.append('../')

from hfstrategy import Strategy
from bfxhfindicators import EMA

# Initialise strategy
strategy = Strategy(
  symbol='tBTCUSD',
  indicators={
    'emaL': EMA([100]),
    'emaS': EMA([20])
  },
  exchange_type=Strategy.ExchangeType.EXCHANGE,
  logLevel='INFO'
)

@strategy.on_enter
async def enter(update):
  emaS = strategy.get_indicators()['emaS']
  emaL = strategy.get_indicators()['emaL']
  if emaS.crossed(emaL.v()):
    if emaS.v() > emaL.v():
      await strategy.open_long_position_market(mtsCreate=update.mts, amount=1)
    else:
      await strategy.open_short_position_market(mtsCreate=update.mts, amount=1)

@strategy.on_update_short
async def update_short(update, position):
  if (position.amount == 0):
コード例 #3
0
import sys
import asyncio
sys.path.append('../')
import time
from hfstrategy import Strategy
from bfxhfindicators import EMA
import nest_asyncio
nest_asyncio.apply()

# Initialise strategy
strategy = Strategy(
    symbol='tBTCUSD',
    indicators={
        # see https://github.com/bitfinexcom/bfx-hf-indicators-py for more info
        'emaL': EMA(100),
        'emaS': EMA(20)
    },
    exchange_type=Strategy.ExchangeType.EXCHANGE,
    logLevel='INFO')


@strategy.on_enter
async def enter(update):
    emaS = strategy.get_indicators()['emaS']
    emaL = strategy.get_indicators()['emaL']
    if emaS.crossed(emaL.v()):
        if emaS.v() > emaL.v():
            await strategy.open_long_position_market(mtsCreate=update.mts,
                                                     amount=1)
        else:
            await strategy.open_short_position_market(mtsCreate=update.mts,
コード例 #4
0
def run_extract_candles():
    # create results folder if it doesn't exist
    if not os.path.exists('results/'):
        os.makedirs('results/')
    # start with blank files
    open('results/below_55.txt', 'w').close()
    open('results/above_55_below_200.txt', 'w').close()
    open('results/above_200.txt', 'w').close()
    
    # load symbols information
    print('Getting list of BTC trade pairs...')
    resp = requests.get(BASE_URL + '/api/v1/ticker/allBookTickers')
    #print(resp.content)
    tickers_list = json.loads(resp.content)
    for ticker in tickers_list:
        if str(ticker['symbol'])[-3:] == 'BTC':
            symbols.append(ticker['symbol'])
    
    # get 4h candles for symbols
    print('Loading candle data for symbols...')
    for sym in symbols:
        #print('BINANCE:' + sym)
        Thread(target=load_candles, args=(sym,)).start()
    while len(candles) < len(symbols):
        print('%s/%s loaded' %(len(candles), len(symbols)), end='\r', flush=True)
        time.sleep(0.1)
    
    # calculate EMAs for each symbol
    print('Calculating EMAs...')
    for sym in candles:
        for period in EMA_PERIODS:
            iEMA = EMA(period)
            lst_candles = candles[sym][:]
            for c in lst_candles:
                iEMA.add(c['close'])
            if sym not in ema_values:
                ema_values[sym] = {}
            ema_values[sym][period] = iEMA.v()
    
    # save filtered EMA results in txt files
    print('Saving filtered EMA results to txt files...')
    for sym in ema_values:
        ema_55 = ema_values[sym][55]
        ema_200 = ema_values[sym][200]
        price = prices[sym]
        entry = ''
        if price < ema_200:
        # save symbols trading below EMA (50)
            f = open('results/below_55.txt', 'a')
            entry = '%s: $%s\n' %(sym, round(price,3))
            f.write(entry)
        elif price > ema_55 and price < ema_200:
        # save symbols trading above EMA(200)
            f = open('results/above_55_below_200.txt', 'a')
            entry = '%s: $%s\n' %(sym, round(price,3))
            f.write(entry)
        elif price > ema_200:
        # save symbols trading above EMA(50) but below EMA(200)
            f = open('results/above_200.txt', 'a')
            entry = '%s: $%s\n' %(sym, round(price,3))
            f.write(entry)
        f.close()
        del f # cleanup
    
    print('All done! Results saved in results folder.')
コード例 #5
0
    if str(ticker['symbol'])[-4:] == 'USDT':
        symbols.append(ticker['symbol'])

# get 4h candles for symbols
print('Loading candle data for symbols...')
for sym in symbols:
    Thread(target=load_candles, args=(sym,)).start()
while len(candles) < len(symbols):
    print('%s/%s loaded' %(len(candles), len(symbols)), end='\r', flush=True)
    time.sleep(0.1)

# calculate EMAs for each symbol
print('Calculating EMAs...')
for sym in candles:
    for period in EMA_PERIODS:
        iEMA = EMA([period])
        lst_candles = candles[sym][:]
        for c in lst_candles:
            iEMA.add(c['close'])
        if sym not in ema_values:
            ema_values[sym] = {}
        ema_values[sym][period] = iEMA.v()

# save filtered EMA results in txt files
print('Saving filtered EMA results to txt files...')
for sym in ema_values:
    ema_50 = ema_values[sym][50]
    ema_200 = ema_values[sym][200]
    price = prices[sym]
    entry = ''
    if price < ema_50:
コード例 #6
0
# import candles for each symbol
Thread(target=show_progress).start() # show progress
for sym in symbols:
    Thread(target=import_candles, args=(sym,)).start()

# wait until all candles are loaded
while go_on == False:
    time.sleep(1)
print('\nAll candles loaded.')

# calculate EMA values
print('Calculating EMA values and scanning for crosses...', end='', flush=True)
for sym in symbols:
    for period in ema_periods:
        iEMA = EMA([period]) # define EMA object
        for candle in candles[sym]:
            iEMA.add(candle['close']) # add all close prices
        lst_ema = []
        lst_ema.append(iEMA.v()) # add current EMA value
        for i in range(historic_window):
            # add historic EMA values
            lst_ema.append(iEMA.prev(i+1))
        if sym not in ema_values: # add symbol key to dictionary
            ema_values[sym] = {}
        ema_values[sym][period] = lst_ema # save EMA values

# identify EMA crosses
ema_results = {
    'cross-downs': [],
    'cross-ups': []
コード例 #7
0
def single_run(ema_l, ema_s, quick_profit_target_percentage,
               profit_target_percentage, stop_loss_percentage):

    # Initialise strategy
    strategy = Strategy(
        symbol='tBTCUSD',
        indicators={
            # see https://github.com/bitfinexcom/bfx-hf-indicators-py for more info
            'emaL': EMA(ema_l),
            'emaS': EMA(ema_s)
        },
        exchange_type=Strategy.ExchangeType.EXCHANGE,
        logLevel='INFO')

    async def enter_long(update):
        amount = 1000 / update.price
        await strategy.open_long_position_market(mtsCreate=update.mts,
                                                 amount=amount)
        # set profit target to 5% above entry
        profit_target = update.price + (update.price *
                                        profit_target_percentage)
        # set a tight stop los of %2 below entry
        stop_loss = update.price - (update.price * stop_loss_percentage)
        # update positions with new targets
        await strategy.set_position_target(profit_target)
        await strategy.set_position_stop(stop_loss)

    async def enter_short(update):
        amount = 1000 / update.price
        await strategy.open_short_position_market(mtsCreate=update.mts,
                                                  amount=amount)
        # same as above, take full proft at 5%
        profit_target = update.price - (update.price *
                                        profit_target_percentage)
        # set stop loss to %2 below entry
        stop_loss = update.price + (update.price * stop_loss_percentage)
        await strategy.set_position_target(profit_target)
        await strategy.set_position_stop(stop_loss)

    @strategy.on_enter
    async def enter(update):
        # We are going to use the ema cross for entrance
        emaS = strategy.get_indicators()['emaS']
        emaL = strategy.get_indicators()['emaL']
        # enter market if ema crosses
        if emaS.crossed(emaL.v()):
            if emaS.v() > emaL.v():
                await enter_long(update)
            else:
                await enter_short(update)

    @strategy.on_update_short
    async def update_short(update, position):
        emaS = strategy.get_indicators()['emaS']
        emaL = strategy.get_indicators()['emaL']
        # if emas cross then just exit the position
        if emaS.v() > emaL.v():
            return await strategy.close_position_market(mtsCreate=update.mts)
        ## if we are up by 2% then take 50% profit and set stop loss to
        ## entry price
        # get entry of initial order
        entry = position.get_entry_order().price
        half_position = abs(position.amount) / 2
        if half_position < 0.1:
            return
        if update.price < entry - (position.price *
                                   quick_profit_target_percentage):
            print("Reached profit target, take 2%")
            await strategy.update_position_market(mtsCreate=update.mts,
                                                  amount=half_position,
                                                  tag="Hit profit target")
            # set our stop loss to be our original entry price
            # here we will set our stop exit type to be a limit order.
            # This will mean we will only be charged maker fees and since we are in profit
            # we dont need to exit the position instantly with a market order
            await strategy.set_position_stop(
                entry, exit_type=Position.ExitType.MARKET)

    @strategy.on_update_long
    async def update_long(update, position):
        emaS = strategy.get_indicators()['emaS']
        emaL = strategy.get_indicators()['emaL']
        # Market is going to change direction so exit position
        if emaS.v() < emaL.v():
            return await strategy.close_position_market(mtsCreate=update.mts)
        # Same as above, take profit at 2% and set stop to entry
        # get entry of initial order
        entry = position.get_entry_order().price
        half_position = abs(position.amount) / 2
        if half_position < 0.1:
            return
        if update.price > entry + (position.price *
                                   quick_profit_target_percentage):
            print("Reached profit target, take 2%")
            await strategy.update_position_market(mtsCreate=update.mts,
                                                  amount=-half_position,
                                                  tag="Hit mid profit target")
            # set our stop loss to be our original entry price
            await strategy.set_position_stop(
                entry, exit_type=Position.ExitType.MARKET)

    from hfstrategy import Executor

    os.mkdir("current_run")

    Executor(strategy, timeframe='1hr',
             show_chart=False).offline(file='btc_candle_data.json')
    # Executor(strategy, timeframe='1m').backtest_live()

    # import time
    # now = int(round(time.time() * 1000))
    # then = now - (1000 * 60 * 60 * 24 * 15) # 15 days ago
    # Executor(strategy, timeframe='30m').with_data_server(then, now)

    with open('current_run/results.json') as json_file:
        total_profit_loss = json.load(json_file)['total_profit_loss']

    shutil.rmtree("current_run")
    return total_profit_loss