Пример #1
0
    def load_level_from_Data(self, data):
        """
                    загружаем предобработанные данные, сгрупированные по дням.
                    Параметры:
                    filename: str Путь до файла с уровнем.
                    verbose: bool
                """

        self.Arch_Data = data
        self.Data = self.Arch_Data
        self.DaysCount = len(self.Data)

        self.days_steps = [len(day[1]) for day in self.Data]
        self.total_steps = sum(self.days_steps)
        self.current_day_vectors = self.Data[self.current_day]
        self.current_day_candles = self.Data[self.current_day][2]
        self.strategy = strat.Strategy(self.current_day_candles)
        self.check_point_ind = -1
        self.check_points = {}
        self.level_finished = False
        self.global_index = []
        for i in range(len(self.Data)):

            for j in range(len(self.Data[i][1])):
                self.global_index.append((i, j))
        self.level_loaded = True

        return
Пример #2
0
    def load_level(self, filename, verbose=True, day_len=-1):
        """
            Функция, загружающая файл с уровнем. Уровень должен быть загружен до начала игры.
            Параметры:
            filename: str Путь до файла с уровнем.
            verbose: bool
        """
        if verbose:
            print(u'Открываем файл ', filename)
        self.Arch_Data = dataIO.load_by_Dates(filename)
        self.Data = self.Arch_Data
        self.DaysCount = len(self.Data)
        if day_len != -1:
            self.apply_data_len(len=day_len)

        self.days_steps = [len(day[1]) for day in self.Data]
        self.total_steps = sum(self.days_steps)
        self.current_day_vectors = self.Data[self.current_day]
        self.current_day_candles = self.Data[self.current_day][2]
        self.strategy = strat.Strategy(self.current_day_candles)
        self.check_point_ind = -1
        self.check_points = {}
        self.level_finished = False
        self.global_index = []
        for i in range(len(self.Data)):

            for j in range(len(self.Data[i][1])):
                self.global_index.append((i, j))
        self.level_loaded = True
        if verbose:
            print('Done: ', self.DaysCount, " days")

        return
Пример #3
0
    def __init__(self):
        self.accountNumber = ''
        self.optionExpiry = '20121221'  # This needs manual updating!
        self.maxAskBidRatio = 1.25
        self.maxAskLastPriceRatio = 1.02
        self.maxOrderQueueLength = 3
        # Create a file for TWS logging
        self.twslog_fh = open('/home/mchan/git/Artemis/twslog.txt', 'a', 0)
        self.twslog_fh.write("Session Started " +
                             str(datetime.datetime.now()) + "\n")
        self.callback = ArtemisIBWrapperSilent.ArtemisIBWrapper()
        self.tws = EPosixClientSocket(self.callback)
        self.orderIdCount = 1  # This will be updated automatically
        self.requestIdCount = 1
        self.invested = False
        self.maxLimitPriceFactor = 1.02  # No limit orders above 2% of current ask price
        # Connect the socket
        self.socketnum = 30
        self.tws.eConnect("", 7496, self.socketnum, poll_interval=1)
        # Strategy Generic object, has methods for interpreting consensus out/under performance
        self.Strat = strategy.Strategy()
        # Queue for orders
        self.orderQueue = []
        # Setup DB connector
        self.db = dbutil.db(h='127.0.0.1', schema='mchan')

        # Query Cash Account Balance
        self.updateBuyingPowerNextId()
Пример #4
0
def test_strategy():
    s = strategy.Strategy('2 0.1 0.0 1.0 1.0 0.0 1.0 0.9 0.1 0.9 0.1')

    assert s._h == 2
    assert np.array_equal(s._p, [0.1, 1.0])
    assert np.array_equal(s._a, [[0.0, 1.0], [0.9, 0.1]])
    assert np.array_equal(s._b, [[1.0, 0.0], [0.9, 0.1]])
Пример #5
0
 def loadStrategies(self,
                    league="all",
                    matchType="all",
                    edge=3,
                    size=10000000000000000,
                    duration=tools.MINUTE * 10,
                    quoter=False,
                    hitter=False):
     """Loads strategies in league specified of type specified
 """
     for m in self.gateway.matches:
         match = self.gateway.matches[m]
         if match.details["expiry"] < tools.curTime():
             continue
         if match.details["league"] != league and league != "all":
             continue
         if match.details["type"] != matchType and matchType != "all":
             continue
         if match.matchName in self.strategiesByMatch:
             if len(self.strategiesByMatch[
                     match.matchName]) >= self.maxStrategiesPerMatch:
                 continue
         else:
             self.strategiesByMatch[match.matchName] = []
         #if we've made it this far, we want to add this match
         self.logger.info(
             "Adding strategy for {0} with edge {1}, size {2}, quoter status {3}, hitter status {4}"
             .format(match.matchName, edge, size, quoter, hitter))
         s = strategy.Strategy(match, edge, size, duration, quoter, hitter)
         idx = len(self.strategies)
         self.strategies.append(s)
         self.strategiesByMatch[match.matchName].append(idx)
Пример #6
0
    def setUp(self):
        self.player = player.Player(1, [], 0)
        self.strat = strategy.Strategy()

        self.carnivore = species.Species(0, 1, 1, [])
        self.carnivore.setTraits([trait.Trait.carnivore])
        self.fat_carnivore = species.Species(0, 1, 1, [])
        self.fat_carnivore.setTraits([trait.Trait.carnivore])
        self.fat_carnivore.setBodySize(5)

        self.herbavore = species.Species(0, 1, 1, [])
        self.fat_herbavore = species.Species(0, 1, 1, [])
        self.fat_herbavore.setBodySize(4)

        self.fat_tissue = species.Species(0, 1, 1, [])
        self.fat_tissue.setBodySize(3)
        self.fat_tissue.setTraits([trait.Trait.fat_tissue])
        self.fat_fat_tissue = species.Species(0, 1, 1, [])
        self.fat_fat_tissue.setBodySize(6)
        self.fat_fat_tissue.setTraits([trait.Trait.fat_tissue])

        self.opherb = species.Species(0, 1, 1, [])
        self.opfatherb = species.Species(0, 1, 1, [])
        self.opfatherb.setBodySize(4)

        self.opponent1 = player.Player(1, [], 0)
        self.opponent1.setSpeciesBoards([self.opherb, self.opfatherb])
        self.opponents = [self.opponent1]

        self.dealer = dealer.Dealer()
        self.dealer.setListOfPlayers([self.player, self.opponent1])
        self.dealer.setWateringHole(4)
Пример #7
0
def test_strategy_prob_for_state():
    s = strategy.Strategy('2 0.1 0.0 1.0 1.0 0.0 1.0 0.9 0.1 0.9 0.1')

    assert np.array_equal(s._prob_for_state(0, 0), [1.0, 0.0])
    assert np.array_equal(s._prob_for_state(0, 1), [0.0, 1.0])
    assert np.array_equal(s._prob_for_state(1, 0), [0.9, 0.1])
    assert np.array_equal(s._prob_for_state(1, 1), [0.9, 0.1])
Пример #8
0
def trade_mock(curr_date, insts=[['IF1412', 'IF1503']]):
    logging.basicConfig(
        filename="ctp_trade_mock.log",
        level=logging.INFO,
        format=
        '%(name)s:%(funcName)s:%(lineno)d:%(asctime)s %(levelname)s %(message)s'
    )
    instruments = list(set(itertools.chain(*insts)))
    data_func = [
            ('d', BaseObject(name = 'ATR_20', sfunc=fcustom(data_handler.ATR, n=20), rfunc=fcustom(data_handler.atr, n=20))), \
            ('d', BaseObject(name = 'DONCH_L10', sfunc=fcustom(data_handler.DONCH_L, n=10), rfunc=fcustom(data_handler.donch_l, n=10))),\
            ('d', BaseObject(name = 'DONCH_H10', sfunc=fcustom(data_handler.DONCH_H, n=10), rfunc=fcustom(data_handler.donch_h, n=10))),\
            ('d', BaseObject(name = 'DONCH_L20', sfunc=fcustom(data_handler.DONCH_L, n=20), rfunc=fcustom(data_handler.donch_l, n=20))),\
            ('d', BaseObject(name = 'DONCH_H20', sfunc=fcustom(data_handler.DONCH_H, n=20), rfunc=fcustom(data_handler.donch_h, n=20))),\
            ('1m',BaseObject(name = 'EMA_3',     sfunc=fcustom(data_handler.EMA, n=3),      rfunc=fcustom(data_handler.ema, n=3))), \
            ('1m',BaseObject(name = 'EMA_30',    sfunc=fcustom(data_handler.EMA, n=30),     rfunc=fcustom(data_handler.ema, n=30))) \
        ]
    test_strat = strat.Strategy('TestStrat', [insts], None, data_func,
                                [[1, -1]])
    strat_cfg = {'strategies': [test_strat], \
                 'folder': 'C:\\dev\\src\\ktlib\\pythonctp\\pyctp\\', \
                 'daily_data_days':25, \
                 'min_data_days':2 }

    agent_name = "Test"
    tday = curr_date
    my_agent, my_trader = create_agent_with_mocktrader(agent_name, instruments,
                                                       strat_cfg, tday)
    my_user = MarketDataMock(my_agent)
    req = BaseObject(InstrumentID='cu1502')
    my_agent.resume()
    my_user.play_tick(tday)
Пример #9
0
def main(argv):

    back_mode = False

    # Either we run in real-time mode with current market data feed
    # or we can force a back-test mode where we give the algorithm the number of days
    # in the past where it should start

    if len(argv) == 0:
        LogPrint("Trader Started Running in Real-Time Mode\n")
    elif len(argv) != 1:
        LogPrint(
            "Usage : Start without Args for Real-Time or -b for backtesting for a number of previous days\n"
        )
        sys.exit(2)
    elif argv[0] != '-b':
        LogPrint(
            "Usage : Start without Args for Real-Time or -b  for backtesting for a number of previous days\n"
        )
        sys.exit(2)
    else:
        back_mode = True

    xreader = xr.XChangeReader()  # init Exchange Data Reader
    strategy = stg.Strategy(
        currency, granularity)  # init strategy with the target currency

    if not back_mode:
        run_realtime(xreader, strategy)
    else:
        run_backtest(xreader, strategy)
Пример #10
0
    def next(self):
        """
        сдвинуть все счетчики на 1
        если переместились в след. день - поменять стратегию
        если находимся в последнем баре, никуда не смещаемся
        """
        if self.current_global_step >= self.total_steps - 1:  # никуда не смещаемся, если дошли до последнего бара
            self.level_finished = True
            return
        _before_day = self.current_day  # запоминаем текущий день
        self.current_global_step += 1  # увеличиваем глобальный шаг на день
        # обновляем счетики дня  счетчик бара внутри дня
        self.current_day, self.current_day_step = self.get_day_step(
            self.current_global_step)

        # если мы переместились в следующий день, то надо поменять стратегию на след день
        if _before_day < self.current_day:
            self.score_without_curr_strat += self.score_by_curr_strat
            self.score_by_curr_strat = 0.0
            self.current_day_candles = self.Data[self.current_day][2]
            self.strategy = strat.Strategy(
                self.current_day_candles)  # создаем новую стратегию
            # print "next day : ", self.current_day
            # так как стратегия поменялась - надо о обновить профиты
        else:
            self.strategy.bar += 1

        return
def test_time():
    ref = ai.Strategy()
    board, player, moves = cases[30]
    tic = time.time()
    for i in range(10000):
        ref.get_valid_moves(board, player)
    toc = time.time()
    print(toc-tic)
Пример #12
0
    def __init__(self, agent, policy=None, K=None):
        self.agent = agent
        self.strategy = strategy.Strategy(self.agent.numactions, policy)

        if K is not None:
            self.K = np.array(K)
        else:
            self.K = np.random.rand(self.agent.opp_numactions)
def test_all():
    ref = ai.Strategy()

    for i in cases:
        board, player, moves = i
        #assert(ref.get_valid_moves(board,player) == i)
        my_moves = ref.get_valid_moves(board, player)
        print(sorted(my_moves), sorted(moves))
        assert(set(my_moves) == set(moves))
Пример #14
0
def test_bollinger():
    myst = st.Strategy()
    mySQL = mysql.MySql()
    # tickers = mySQL.get_tickers_id()
    tickers = ['WPRT', 'WPRTT', 'WELL']
    # exclude = tickers
    # tickers = mySQL.get_tickers_id()
    # tickers = [ticker for ticker in tickers if ticker not in exclude]
    # tickers = [ticker for ticker in tickers if ticker > 'TCS']

    myst.bollinger_short_trend_back(
        tickers, dt.datetime.strptime("2019-01-01", "%Y-%m-%d"))
Пример #15
0
def from_genes(genes):
    num_genes = len(genes)
    assert num_genes % 3 == 0
    # H
    h = int(num_genes / 3)
    # P
    p = np.array(genes[:h]).reshape(h)
    # A
    a = np.array(genes[h:2 * h])
    # B
    b = np.array(genes[2 * h:3 * h])

    return Individual(strategy.Strategy((h, p, a, b)))
Пример #16
0
 def reset_level(self):
     '''
     Сбрасываем бота в начальне состояние.
     '''
     self.current_day_step = 0
     self.current_day = 0
     self.current_global_step = 0
     self.current_day_candles = self.Data[self.current_day][2]
     self.strategy = strat.Strategy(self.current_day_candles)
     self.score = 0.0
     self.score_by_curr_strat = 0.0
     self.score_without_curr_strat = 0.0
     self.level_finished = False
     return
Пример #17
0
def _random_strategy(h):
    # Create random p vector
    p = np.random.uniform(size=h)
    logging.debug('P:\n%s\n', p)

    # Create random A transition matrix where rows sum to 1.0
    a = np.random.dirichlet(np.ones(h), size=h)
    logging.debug('A (sum=%s):\n%s\n', a.sum(axis=1), a)
    assert np.allclose(a.sum(axis=1), np.ones(h))

    # Create random B transition matrix where rows sum to 1.0
    b = np.random.dirichlet(np.ones(h), size=h)
    logging.debug('B (sum=%s):\n%s\n', b.sum(axis=1), b)
    assert np.allclose(b.sum(axis=1), np.ones(h))

    return strategy.Strategy((h, p, a, b))
Пример #18
0
def semi_mock(curr_date, user_cfg, insts=[['IF1412', 'IF1503']]):
    ''' 半模拟
        实际行情,mock交易
    '''
    logging.basicConfig(
        filename="ctp_semi_mock.log",
        level=logging.INFO,
        format=
        '%(name)s:%(funcName)s:%(lineno)d:%(asctime)s %(levelname)s %(message)s'
    )
    instruments = list(set(itertools.chain(*insts)))
    data_func = [
            ('d', BaseObject(name = 'ATR_20', sfunc=fcustom(data_handler.ATR, n=20), rfunc=fcustom(data_handler.atr, n=20))), \
            ('d', BaseObject(name = 'DONCH_L10', sfunc=fcustom(data_handler.DONCH_L, n=10), rfunc=fcustom(data_handler.donch_l, n=10))),\
            ('d', BaseObject(name = 'DONCH_H10', sfunc=fcustom(data_handler.DONCH_H, n=10), rfunc=fcustom(data_handler.donch_h, n=10))),\
            ('d', BaseObject(name = 'DONCH_L20', sfunc=fcustom(data_handler.DONCH_L, n=20), rfunc=fcustom(data_handler.donch_l, n=20))),\
            ('d', BaseObject(name = 'DONCH_H20', sfunc=fcustom(data_handler.DONCH_H, n=20), rfunc=fcustom(data_handler.donch_h, n=20))),\
            ('1m',BaseObject(name = 'EMA_3',     sfunc=fcustom(data_handler.EMA, n=3),      rfunc=fcustom(data_handler.ema, n=3))), \
            ('1m',BaseObject(name = 'EMA_30',    sfunc=fcustom(data_handler.EMA, n=30),     rfunc=fcustom(data_handler.ema, n=30))) \
        ]
    test_strat = strat.Strategy('TestStrat', [insts], None, data_func,
                                [[1, -1]])
    strat_cfg = {'strategies': [test_strat], \
                 'folder': 'C:\\dev\\src\\ktlib\\pythonctp\\pyctp\\', \
                 'daily_data_days':25, \
                 'min_data_days':2 }

    agent_name = "Test"
    tday = curr_date
    my_agent, my_trader = create_agent_with_mocktrader(agent_name, instruments,
                                                       strat_cfg, tday)
    ctp_api.make_user(my_agent, user_cfg)

    req = BaseObject(InstrumentID='cu1502')
    my_trader.ReqQryInstrumentMarginRate(req)
    my_trader.ReqQryInstrument(req)
    my_trader.ReqQryTradingAccount(req)

    my_agent.resume()

    try:
        while 1:
            time.sleep(1)
    except KeyboardInterrupt:
        my_agent.mdapis = []
        my_agent.trader = None
    pass
Пример #19
0
 def __init__(self, ahk, c_model):
     self.controller = controls.Control(ahk)
     self.gold = 1
     self.round = 1
     self.char_model = c_model
     self.exp = 0
     self.level = 1
     self.check_levelup()
     self.bag_items = 0
     self.deployed_chars = 0
     self.chars_on_bench = 0
     self.bench_full = False
     self.board_list = []
     self.bench_list = []
     self.store = Store(c_model)
     self.init_lists()
     self.strategy = strategy.Strategy()
     self.strategy.set_strategy(strategy.WARRIORS)
Пример #20
0
    def set_sample_days(self, days_to_sample=1):
        self.Data = random.sample(self.Arch_Data, days_to_sample)
        self.DaysCount = len(self.Data)

        self.days_steps = [len(day[1]) for day in self.Data]
        self.total_steps = sum(self.days_steps)
        self.current_day_vectors = self.Data[self.current_day]
        self.current_day_candles = self.Data[self.current_day][2]
        self.strategy = strat.Strategy(self.current_day_candles)
        self.check_point_ind = -1
        self.check_points = {}
        self.level_finished = False
        self.global_index = []
        for i in range(len(self.Data)):

            for j in range(len(self.Data[i][1])):
                self.global_index.append((i, j))
        self.level_loaded = True

        return
Пример #21
0
def getPathToFollow(problem, initPoint, finalPoint):
    startT = time.time()

    prob = strategy.Problem(problem, problem[initPoint], problem[finalPoint])
    srh = strategy.Search()
    final = srh.ngraphSearch(prob, strategy.Strategy(strategy.Strategy.STRATEGY['A*']))
    
    endT = time.time()
    pathFollowed = []

    if final is False:
        print("Position unreachable")
        return

    while final is not None:
        pathFollowed.append(final.getTail().name)
        final = final.getParentPath()

    pathFollowed.reverse()
    print(pathFollowed)
    print("Search time", endT - startT)

    return pathFollowed
Пример #22
0
import strategy as ai

ref = ai.Strategy()
next_board = ref.get_starting_board()
infile = open("moves.txt", "r")
counter = 0
for line in infile.readlines():
    counter += 1
    board, player, move = line.strip().split(" ")
    print("testing line %i" % counter)
    assert(board == next_board)
    next_board = ref.make_move(board, player, int(move))
if counter == 60: print("All Tests Pass!")
infile.close()
Пример #23
0
def main():
    '''main method that prompts the user for input'''
    global ai
    global gameBoard
    global playerColor
    # print("\nWelcome to Kyle's Gomoku AI!")
    os.system("")  # allows colored terminal to work on Windows OS
    printAsciiTitleArt()
    boardDimension = input(
        "What is the dimension of the board? (Default is 13x13)\nEnter a single odd number:\t"
    ).strip()
    if boardDimension.isdigit(
    ) and int(boardDimension) % 2 == 1 and 6 < int(boardDimension) < 100:
        print("The board will be %sx%s!" % (boardDimension, boardDimension))
    else:
        boardDimension = 13
        print("Invalid input. The board will be 13x13!")
    createGameBoard(int(boardDimension))
    playerColorInput = input(
        "Would you like to be BLACK ('b') or WHITE ('w')? (black goes first!):\t"
    ).strip().lower()
    if playerColorInput == 'b':
        playerColor = BLACK
        print("You will be black!")
    else:
        playerColor = WHITE
        if playerColorInput == 'w':
            print("You will be white!")
        else:
            print("Invalid input. You'll be white!")

    ai = strategy.Strategy(int(boardDimension), playerColor)
    print(f"\nYou: {MY_COLOR}%s{NO_COLOR}\tAI: {ENEMY_COLOR}%s{NO_COLOR}" %
          (playerColor, ai.opponentOf(playerColor)))
    print(
        "Press 'q' at any prompt to quit.\nOr, press 'p' to end the game and receive Python code for recreating the gameBoard."
    )
    turn = BLACK
    columnLabels = list(map(chr, range(65, 65 + len(gameBoard))))
    mostRecentMove = None

    while not ai.GAME_OVER:
        printGameBoard(mostRecentMove)
        if turn == playerColor:
            mostRecentMove = getPlayerMove()
        else:
            userInput = input(
                "It's the AI's turn, press enter for it to play.\t").strip(
                ).lower()
            while userInput == 'q' or userInput == 'p':
                if userInput == 'q':
                    print("\nThanks for playing!\n")
                    exit(0)
                else:
                    givePythonCodeForBoardInput()
                    userInput = input(
                        "Press enter for the AI to play, or press 'q' to quit:\t"
                    ).strip().lower()
            startTime = time.time()
            ai_move_row, ai_move_col = ai.playBestMove(gameBoard)
            endTime = time.time()
            minutesTaken, secondsTaken = int(endTime - startTime) // 60, (
                endTime - startTime) % 60
            print("Time taken: %s %.2fs" %
                  ('' if minutesTaken == 0 else '%dm' % minutesTaken,
                   secondsTaken))
            ai_move_formatted = columnLabels[ai_move_col] + str(ai_move_row +
                                                                1)
            print("AI played in spot %s\n" % ai_move_formatted)
            mostRecentMove = [ai_move_row, ai_move_col]
        turn = ai.opponentOf(turn)  # switch the turn

    printGameBoard(mostRecentMove)
    boardCompletelyFilled = True
    for row in gameBoard:
        for spot in row:
            if spot == EMPTY:
                boardCompletelyFilled = False
                break

    if boardCompletelyFilled:
        print("Nobody wins, it's a tie!")
    else:
        winner = "BLACK" if ai.opponentOf(turn) == BLACK else "WHITE"
        print("%s wins!\n" % winner)
Пример #24
0
 def __init__(self, ident, loSpeciesBoard, bag):
     self.species_boards = loSpeciesBoard
     self.food_bag = bag
     self.hand = []
     self.player_id = ident
     self.strat = strategy.Strategy()
Пример #25
0
 def start(self):
     while True:
         task = strategy.Strategy(self.queue, self.batch_size)
         task.start()
         time.sleep(5)
Пример #26
0
                    for x in range(1, idDiff):
                        intList.addInterval(Interval(intList.intList[-1],
                                                     True))
                        intList.printIntervalAt(-1)
            intList.addInterval(curInterval)
        else:
            curInterval.addTrade(curTrade)
    print "Complete!"

mtgox = GoxAPI()
mtgox.connect()

mtgoxThread = GoxAPI()
mtgoxThread.connect()

tradeStrategy = strategy.Strategy(intList)

thread.start_new_thread(tradeStrategy.run, (mtgoxThread, ))

while True:
    """Main program loop

    Will keep recieving trade data until process dies
    """
    if (args.testMode):
        time.sleep(5)
        mtTrade = {
            'date': time.time(),
            'price': random.uniform(88, 98),
            'amount': random.uniform(0.01, 3.0)
        }
Пример #27
0
if restart == True:
    spot = pickle.load(open("spot.p", "rb"))
elif restart == False:
    spot = {'block': 0, 'val': 0}
else:
    restart = True
    spot = {'block': 0, 'val': 0}
pickle.dump(spot, open("spot.py", "wb"))

HardLogic = lg.HardLogic(restart)
SoftLogic = lg.SoftLogic(restart)
SplittingLogic = lg.SplittingLogic(restart)
FirstCardLogic = lg.FirstCardLogic(restart)

RandomGen = rg.RandomGenerator(randomNumberSeed)
Strategy = st.Strategy(SplittingLogic.splittingTest, SoftLogic.softTest,
                       HardLogic.hardTest, FirstCardLogic.firstTest)

starttime = time.time()
payOff = []
for q in range(1, games):
    payOff.append(g.game(hands, decks, Strategy, RandomGen))

incumbent = sum(payOff) / len(payOff)
print(
    "intial incumbent established " + str(time.time() - starttime) + " value=",
    str(incumbent))

if spot['block'] < 1:
    if spot['val'] == 0:
        i = 6
    else:
Пример #28
0
# TJHSST
#

# change the following one line to your strategy file name
import strategy as ai
import Othello_human as human
import Othello_Core as core  ## to access constants directly

## in my client, I will import MY core file to run the game, but for testing you can just
## use your own

import time
from multiprocessing import Process, Value
import os, signal

ai1 = ai.Strategy()  ### your strategy object
ai2 = human.Strategy(
)  ## make this different to play 2 different strategy files


def tournament_player(black_choice,
                      white_choice,
                      black_name="Black",
                      white_name="White",
                      time_limit=5):
    """ runs a tournament of an even number of games, alternating black/white with each strategy
        and returns the results """
    ai1_wins = 0
    rounds = 1
    for i in range(2 * rounds):
        try:
Пример #29
0
    def create_primary_strategy(self):
        # primary strategy
        s3 = strategy.Strategy(self.db,
                               self.tele,
                               name='primary',
                               color='teal',
                               order=1)

        # BUY
        c1 = condition.Condition(function='percentage_to_last',
                                 operator='>',
                                 value=0.01)
        c2 = condition.Condition(function='trend_of_last_seconds',
                                 param=70,
                                 operator='<',
                                 value=-0.24)
        s3.add_should_buy([c1, c2], text='percentage to last is positive')

        c1 = condition.Condition(function='percentage_to_last',
                                 operator='>',
                                 value=0)
        c2 = condition.Condition(function='trend_of_last_seconds',
                                 param=70,
                                 operator='<',
                                 value=0.4)
        s3.add_should_buy([c1, c2], text='percentage to last is positive')

        # c = condition.Condition(function='percentage_to_last', operator='<', value=-0.03)
        # s3.add_should_buy([c], text='high loss in cur tick')

        # SELL
        c1 = condition.Condition(function='percentage_to_last',
                                 operator='<',
                                 value=-0.01)
        c2 = condition.Condition(function='trade.percentage',
                                 operator='>=',
                                 value=0)
        s3.add_should_sell([c1, c2],
                           text='high loss in cur tick and has profit')

        c1 = condition.Condition(function='percentage_to_last',
                                 operator='<',
                                 value=0)
        c2 = condition.Condition(function='trade.percentage',
                                 operator='<',
                                 value=-0.4)
        s3.add_should_sell(
            [c1, c2],
            text='percentage to last is negative and profit is lower than -0.4%'
        )

        # c = condition.Condition(function='trend_of_last_seconds', param=30, operator='<', value=0.005)
        # s3.add_should_sell([c], text='no significant change in last 30 seconds')

        c = condition.Condition(function='trade.percentage',
                                operator='>=',
                                value=1)
        s3.add_should_sell([c], text='enough profit (>0.1%)')

        # c = condition.Condition(function='trend_of_last_seconds', param=10, operator='<', value=0)
        # s3.add_should_sell([c], text='no positive trend in last 10 seconds')

        c1 = condition.Condition(function='trade.percentage',
                                 operator='>=',
                                 value=0)
        c2 = condition.Condition(function='trade.last_percentage',
                                 operator='<',
                                 value=0)
        s3.add_should_sell([c1, c2], text='has profit, after no profit')

        self.strategies.append(s3)
Пример #30
0
YELLOW_COLOR = "\u001b[38;5;226m"  # yellow
RED_COLOR = '\033[91m'  # red
BLUE_COLOR = "\u001b[38;5;39m"  # blue
NO_COLOR = '\033[0m'  # white

EMPTY, RED, YELLOW = '.', 'o', '@'
gameBoard = [
    [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY],  # bottom row
    [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY],
    [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY],
    [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY],
    [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY],
    [EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY]
]  # top row
playerColor = YELLOW
ai = strategy.Strategy()


def printBoard(board):
    '''Prints the given game board'''
    print("\n  1 2 3 4 5 6 7")
    for rowNum in range(len(board) - 1, -1, -1):
        print(f"{BLUE_COLOR}|{NO_COLOR} ", end='')
        for spot in board[rowNum]:
            if spot == RED:
                pieceColor = RED_COLOR
            elif spot == YELLOW:
                pieceColor = YELLOW_COLOR
            else:
                pieceColor = NO_COLOR
            print(f"{pieceColor}%s{NO_COLOR} " % spot, end='')