def run(self, startWith='BUY'): print("Trades begin") start_time = datetime.utcnow() reset_interval = self.calculate_timedelta('2h') uptime = datetime.utcnow() - start_time # Terminate when given time is reached while (self.runtime > datetime.utcnow() - start_time): try: # Reset the client every 2 hours if uptime > reset_interval: self.user.reset_client() uptime -= reset_interval # Create dataframe and fill MACD, RSI columns klines = self.create_dataframe() macd = Strategy('MACD','CROSSOVER',self.symbol,self.trade_interval,klines) rsi = Strategy('RSI','OVERBOUGHT',self.symbol,self.trade_interval,klines) # Macd indicator to determine to buy or sell macd_signal = 'HOLD' # Operation to perform next (either BUY or SELL) next_operation = startWith # Rsi value for last kline rsi_indicator = rsi.get_result()[-1][1] # Make sure timestamps match if macd.get_result()[-1][0] == klines.index[-1]: macd_signal = macd.get_result()[-1][2] else: macd_signal = 'HOLD' # Perform the trade or don't based on macd_signal # Amount to be traded is determined by the RSI indicator # Above 70 and below 30 are considered as the low-risk zones if next_operation == macd_signal: order = False if next_operation == 'BUY': if rsi_indicator <= 30: order = self.user.buy_market(self.symbol, 70) next_operation = 'SELL' elif rsi_indicator <= 50: order = self.user.buy_market(self.symbol, 30) next_operation = 'SELL' elif next_operation == 'SELL': if rsi_indicator >= 70: order = self.user.sell_market(self.symbol, 100) next_operation = 'BUY' elif rsi_indicator >= 50: order = self.user.sell_market(self.symbol, 50) next_operation = 'BUY' if order != False: self.showMessage(order) # Handles requests' read operation timeouts except exceptions.ReadTimeout: print('Read timeout') # Sleep in order to avoid timeouts time.sleep(15)
def nextGeneration(self, tetronimoes): scores = [(strategy, strategy.score(tetronimoes)) for strategy in self.strategies] scores.sort(reverse=True, key=lambda x: x[1]) # keep best 25% self.strategies = [] for i in range(int(self.size / 4)): self.strategies.append(scores[i][0]) # generate 10% new data for the gene pool for _ in range(int(self.size / 10)): self.strategies.append( Strategy.generateRandomStrategy(self.functions)) # for 10% of the data, randomly select 20% of the data, swap a weight in best 2 for _ in range(int(self.size / 10)): subset = random.sample(scores, int(self.size / 5)) subset.sort(reverse=True, key=lambda x: x[1]) index = random.sample( [i for i in range(len(subset[0][0].weights))], 2) subset[0][0].weights[index[0]], subset[0][0].weights[ index[1]] = subset[0][0].weights[ index[1]], subset[0][0].weights[index[0]] self.strategies.append( Strategy(self.functions, subset[0][0].weights)) # fill the rest of the strategies with evolved data # randomly select 20% of the data, average the best 2 while len(self.strategies) < self.size: subset = [] if self.size >= 10: subset = random.sample(scores, int(self.size / 5)) else: subset = random.sample(scores, 2) subset.sort(reverse=True, key=lambda x: x[1]) weights = [ subset[0][0].weights[f] + subset[1][0].weights[f] for f in range(len(self.functions)) ] weightnorm = pow(sum(w**2 for w in weights), 0.5) weights = [w / weightnorm for w in weights] self.strategies.append(Strategy(self.functions, weights)) #replace repeating stratagies with random weights self.strategies.sort(reverse=True, key=lambda x: x.weights[0]) for i in range(self.size): if i != 0 and self.strategies[i - 1].weights == self.strategies[i]: self.strategies[i - 1] = generateRandomStrategy(self.functions) return scores, sum(score for (_, score) in scores) / len(scores)
def plot(self, indicator): klines = self.create_dataframe() if indicator == 'MACD': st = Strategy('MACD','CROSSOVER',self.symbol,self.trade_interval,klines) elif indicator == 'SMA': st = Strategy('SMA','CROSSOVER',self.symbol,self.trade_interval,klines) elif indicator == 'RSI': st = Strategy('RSI','OVERBOUGHT',self.symbol,self.trade_interval,klines) else: return False st.plotIndicator()
def test_available_moves(): g = Game(Strategy(), Strategy()) s = g.state moves = available_moves(s) for m in moves: new_state = deepcopy(g.state) new_state.apply(m) new_state.show() return moves
def __init__(self, randomForestModel=None): self.board = Board() self.currentPlayerIndex = 0 self.winner = None self.strategies = { Y: Strategy('Y', strategy="random"), G: Strategy('G', strategy="random"), B: Strategy('B', strategy="random"), R: Strategy('R', strategy="random") } self.totalTurns = 0 self.sorryCount = {Y: 0, G: 0, B: 0, R: 0} self.lostTurns = {Y: 0, G: 0, B: 0, R: 0} self.killedPawnSpots = {} self.states = []
def test_init(self): # strategy name should be more than 3 char long with self.assertRaises(ValueError): strat = Strategy(name="", signal_method=None) # strategy name should be a string with self.assertRaises(ValueError): strat = Strategy(name=5, signal_method=None) # signal method is a must with self.assertRaises(ValueError): strat = Strategy(name="mean deviation", signal_method=None) strat = Strategy(name='mean deviation', signal_method=mean_deviation)
def __init__(self, strategy): self.probability = 0.5 self.payoffs = [] self.lastPayoff = 0 self.strategy = Strategy(strategy) self.action = "" self.pastActions = []
def __init__(self, strat=None, load=False): #initialise the strategy with the file name and whether to load or create a fresh file self.strategy = Strategy(strat, load) #simple dict to convert between char and int value for decisions self.opt_dict = {'f': 0, 'x': 1, 'c': 2, 'b': 3, 'r': 4} #initialise current hand self.current_hand = []
def __init__(self, screen_size): self.screen = pygame.display.set_mode(screen_size, pygame.FULLSCREEN) self.screen.fill([255, 255, 255]) self.map = Map(self.screen, screen_size) self.strategy = Strategy(self.screen, screen_size) self.information = Information(self.screen, screen_size) self.fullmap = FullMap(self.screen, screen_size)
def __init__(self): """ Load your agent here and initialize anything needed WARNING: any path to files you wish to access on the docker should be ABSOLUTE PATHS """ # functional modules self.perception = Perception( self ) # generate high-level perception based on current observation self.strategy = Strategy( self ) # implement strategy to chase the food given the high-level perception self.action_state_machine = ActionStateMachine( self) # use a finite state machine to help implement the strategy self.chaser = Chaser(self) # responsible for chase the food # primitive perception self.obs_visual = None # visual input in RGB space, float numpy array of shape (84, 84, 3) self.obs_visual_hsv = None # visual input in HSV space, float numpy array of shape (84, 84, 3) self.obs_vector = None # speed vector (left-right, up-down, forward-backward), float numpy array of shape (3,) self.done = None # if the current test is done, bool self.reward = None # current reward from the env, float self.info = None # the brainInfo object from the env self.t = None # how long will this test last? int self.step_n = None # the current time step, int # high-level perceptions # Thought the environment is 3D, all the representation here is in the 2D plane of images. self.is_green = None # bool numpy array of shape (84, 84), to indicate if each pixel is green (food color) self.is_brown = None # bool numpy array of shape (84, 84), to indicate if each pixel is brown (food color) self.is_red = None # bool numpy array of shape (84, 84), to indicate if each pixel is red (danger color) self.is_blue = None # bool numpy array of shape (84, 84), to indicate if each pixel is blue (sky color) self.is_gray = None # bool numpy array of shape (84, 84), to indicate if each pixel is gray (wall color) self.target_color = None # the color is currently looking for, either brown or green self.is_inaccessible = None # bool numpy array of shape (84, 84), to indicate if each pixel is inaccessible # because it might be a wall pixel, sky pixel or a dangerous pixel. self.is_inaccessible_masked = None # bool numpy array of shape (84, 84), is_inaccessible # without the pixels on the four sides set to be accessible forcefully. self.reachable_target_idx = None # int numpy array of (2,), to indicate where the target is in the visual input self.reachable_target_size = None # int, to indicate how many pixels in the target self.nearest_inaccessible_idx = None # int numpy array of (2,), to indicate the nearest inaccessible pixel # memory use queues as memory to save the previous observation self.is_green_memory = queue.Queue(maxsize=AgentConstants.memory_size) self.is_brown_memory = queue.Queue(maxsize=AgentConstants.memory_size) self.is_red_memory = queue.Queue(maxsize=AgentConstants.memory_size) self.vector_memory = queue.Queue(maxsize=AgentConstants.memory_size) # the action that will be returned to the env self.current_action = None # strategy-related variables self.pirouette_step_n = None # int, counting the how long the agent has remain static and rotating self.target_color = None # the color that the agent is looking for, either "green" or "brown" self.exploratory_direction = None # int, if nowhere to go, go in this direction self.not_seeing_target_step_n = None # int, how long the agent has lost the visual of a target self.chase_failed = None # bool, if it failed to reach a target because path planning failed self.search_direction = None # either left or right, to start searching for the target self.static_step_n = None # int, how long the agent's position hasn't changed
def build_strategy(): γ = 0.99 α = 0.1 λ = 0.1 ε = 0.1 ε_decay = 1 return Strategy(γ, α, λ, ε, ε_decay, Environment.actions)
def __init__(self, person, team): """Initialize a Manager object.""" self.person = person # The person in whom this manager layer embeds person.manager = self self.career = ManagerCareer(manager=self) self.team = team self.strategy = Strategy(owner=self)
def CreateString(n, k): initialValue = 'A' * n char_list = list(initialValue) h = Strategy(k) candidates = SortedListWithKey(key=h.evaluate_node) candidates.add(char_list) altura = 0 while altura < k + 1: try: candidate = candidates.pop(0) punctuation = h.evaluate_node(candidate) if punctuation == 0: return ''.join(candidate) l = expand(candidate) for expanded in l: punctuation = h.evaluate_node(expanded) if punctuation >= 0: candidates.add(expanded) altura += 1 except IndexError: return '' return ''
def trefun(self, event): curItem = self.tree.focus() line_id = self.tree.item(curItem)['text'] Hid = Strategy(line_id, self.chess, self.equip, self.job, self.race, self.root.winfo_width()) Hid.show()
def _build_strategies(self): """ + Description: build strategies based on algorithms. + Input: - + Output: - """ self.strategies = {} for element in self.strategies_elements: key = element[definitions.strategy_id] threshold = element[definitions.threshold] algorithm_ids = element[definitions.algorithms_array] algorithms = [self.algorithms[algo_id] for algo_id in algorithm_ids] data_modules = set() for algorithm_id in algorithm_ids: if algorithm_id in element[definitions.algorithms_array]: data_modules.update(self.algorithms[algorithm_id].data_modules) self.strategies[key] = Strategy(key, threshold, self.request_pile, self.request_flag, algorithms, data_modules, self.portfolio, self.trading) print("\nStrategies:") pprint(self.strategies)
def test_strategy_instance(self): s = Strategy(start_amount=1000, sl=0.02, tpmulti=2, leverage=1) # Check whether basic properties where set correctly. self.assertEqual(s.options['start_amount'], 1000) self.assertEqual(s.options['stop_loss'], 0.02) self.assertEqual(s.options['tpmulti'], 2) self.assertEqual(s.options['transaction_size'], 10) self.assertEqual(s.options['max_open_positions'], 10) # Statistics properties are set to zero. self.assertEqual(s.stats['trades_count'], 0) self.assertEqual(s.stats['positive_count'], 0) self.assertEqual(s.stats['negative_count'], 0) self.assertEqual(s.stats['balance_highest'], 0) self.assertEqual(s.stats['balance_lowest'], 0) self.assertEqual(s.stats['positive_max_in_row'], 0) self.assertEqual(s.stats['negative_max_in_row'], 0) # Properties in status. self.assertEqual(s.status['remaining_amount'], s.options['start_amount']) self.assertEqual(s.status['open_trades_count'], 0) self.assertEqual(s.status['closed_trades_count'], 0) # Property that cache trades made. At the beginning this # property should be empty. self.assertEqual(s.trades, [])
def __init__(self): self.live_trading = True # set False for backtesting. self.log_level = logging.DEBUG self.logger = self.setup_logger() # Don't connect to live data feeds if backtesting. if self.live_trading: self.exchanges = self.load_exchanges(self.logger) # Connect to database. print("Connecting to database...") self.db_client = MongoClient( self.DB_URL, serverSelectionTimeoutMS=self.DB_TIMEOUT_MS) self.db = self.db_client[self.DB_NAME] self.check_db_connection() # Event queue and producer/consumer worker classes. self.events = queue.Queue(0) self.data = Datahandler(self.exchanges, self.logger, self.db, self.db_client) self.strategy = Strategy(self.exchanges, self.logger, self.db, self.db_client) self.portfolio = Portfolio(self.logger) self.broker = Broker(self.exchanges, self.logger) # Processing performance variables. self.start_processing = None self.end_processing = None self.run()
def main(argv): chart = Chart("bittrex", "BTC-LTC", "fiveMin", False) logger = Logger strategy = Strategy(capital=0.01, pair="BTC-LTC", client=chart.conn) # candlesticks = [] # developing_candlestick = BotCandlestick() while True: try: price = chart.get_current_price() except Exception as e: logger.log("ERROR: Exception occurred: " + e.message, "error") time.sleep(int(1)) price = chart.get_current_price() logger.log("Received price: " + str(price)) strategy.live_tick(price) # if developing_candlestick.is_closed(): # candlesticks.append(developing_candlestick) # strategy.tick(developing_candlestick) # developing_candlestick = BotCandlestick() time.sleep(int(1))
def run_simulation(lead_exchange_name, lag_exchange_name, lead_symbol, lag_symbol, taker_fee, maker_fee, from_date, to_date, time_diff, target_percentage, stop_percentage): feed = virtual.Feed() lag_exchange = virtual.Exchange(exchange=lag_exchange_name, taker_fee=taker_fee, maker_fee=maker_fee) lead_lag_strat = Strategy( lead_exchange_name=lead_exchange_name, lag_exchange=lag_exchange, lag_symbol=lag_symbol, time_diff=time_diff, target_percentage=target_percentage, stop_percentage=stop_percentage, ) feed.subscribe("trades", lead_lag_strat.on_trade) lag_exchange.subscribe("updates", lead_lag_strat.on_updates) # lag_exchange.attach_feed(feed) print("Starting feed!") feed.start(exchanges=[lead_exchange_name, lag_exchange_name], symbols=[lead_symbol, lag_symbol], from_date=from_date, to_date=to_date) print("Done with feed") print(lag_exchange.wallets) datenow = datetime.now().isoformat() with open(f"results/results_{datenow}.json", "w") as file: json.dump(lead_lag_strat.updates, file)
def __init__(self): self.camera = Camera(None, draw=False) self.display_camera = Camera(None, window_name='labeled') centers = [] with open('centers.txt', encoding='utf-8', mode='r') as file: for line in file: center = tuple(map(float, line.strip().split(' '))) centers.append(center) self.centers = centers self.graph_builder = GraphBuilder(self.centers) self.orders = ['thief', 'policeman1', 'policeman2'] self.strategy = Strategy(self.orders) self.object_list = { "thief": { "confidence": 0.99, "center": self.centers[6], # (width,height) "size": (0.15, 0.10), # (width,height) }, "policeman1": { "confidence": 0.99, "center": self.centers[1], # (width,height) "size": (0.15, 0.05), # (width,height) }, "policeman2": { "confidence": 0.99, "center": self.centers[3], # (width,height) "size": (0.15, 0.05), # (width,height) } } self.counter = 0 self.thief_movements = [13, 14, 15, 16] self.escape_nodes = {10} self.graph = None self.objects_on_graph = None self.instructions = None
def __init__(self, env, history_len=5, train_pool_size=64, allowed_feedback_pos=5, feedback_weight=1, like_weight=1): '''Initialize necessary setup according to environment. Args: env: specify the environment history_len(default=5): how many steps you want your state represent train_pool_size(default=512): experience replay pool allowed_feedback_pos(default=5): If user feedback position is greater than this value, agent would get negative reward. feedback_weight(default=1): Weight the feedback position. like_weight(default=1): Weight the final like signal. ''' self.env = env self.history = deque(maxlen=history_len) self.train_pool_size = train_pool_size self.training_pool = deque(maxlen=train_pool_size) self.rev_action_dict = self.env.get_actions() # index to actions self.action_dict = { action: ind \ for ind, action in enumerate(self.rev_action_dict) } self.action_num = len(self.action_dict) self.state_dim = 7 self.strategy = Strategy(self.action_num, self.state_dim) self.allowed_feedback_pos = allowed_feedback_pos self.feedback_weight = feedback_weight self.like_weight = like_weight
def __init__(self): self.logger = self.set_logger() self.logger.info('Main start') self.app = QApplication(sys.argv) self.kiwoom = Strategy() self.app.exec_()
def test_zig_zag(self): board = Board(2, 5, {0: [0, 1]}, num_of_fish_per_tile=2) state = GameState(board, {1: "black", 2: "white"}, [2, 1], penguin_posns={1: [[0, 0], [0, 1], [0,2], []], 2: [[1, 0], [1, 1], [], []]}) strategy = Strategy(state, 2) assert strategy.zig_zag() == [0,3] state = GameState(board, {1: "black", 2: "white"}, [1, 2], penguin_posns={1: [[0, 0], [0, 1], [0, 2], []], 2: [[1, 0], [1, 1], [0, 3], []]}) strategy = Strategy(state, 1) assert strategy.zig_zag() == [0,4] state = GameState(board, {1: "black", 2: "white"}, [2, 1], penguin_posns={1: [[0, 0], [0, 1], [0, 2], [0, 4]], 2: [[1, 0], [1, 1], [0, 3], []]}) strategy = Strategy(state, 2) assert strategy.zig_zag() == [1,2]
def test_which_action_to_take_one_turn(self): board = Board(2, 5, {}, num_of_fish_per_tile=2) state = GameState(board, {1: "black", 2: "white"}, [2, 1], penguin_posns={1: [[0, 0], [0, 1], [0, 2], [1, 3]], 2: [[1, 0], [1, 1], [1, 2], [1, 4]]}) strategy = Strategy(state, 2) assert strategy.which_action_to_take(1) == ((1, 2), (0, 3))
def __init__(self): self.color = '' self.strategy = Strategy() self.starting_positions = [Position(0, 0), Position(0, 4), Position(4, 4), Position(4, 0)] self.RuleChecker = RuleChecker() self.game_state = 'start' self.name = 'Kanye' self.last_board = Board([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
def test_which_action_invalid_input(self): board = Board(2, 5, {}, num_of_fish_per_tile=2) state = GameState(board, {1: "black", 2: "white"}, [2, 1], penguin_posns={1: [[0, 0], [0, 1], [0, 2], [1, 3]], 2: [[1, 0], [1, 1], [1, 2], [1, 4]]}) strategy = Strategy(state, 2) with self.assertRaises(ValueError): strategy.which_action_to_take(0)
def __init__(self, type): self.debug = Debug() self.strategy = None self.color = type try: from strategy import Strategy self.strategy = Strategy(self.debug, self.color) except Exception as e: self.debug.exception(str(e))
def test_which_action_to_take_tiebreaker(self): # tests both cases of the tiebreaker board = Board(2, 5, {}) state = GameState(board, {1: "black", 2: "white"}, [1, 2], penguin_posns={1: [[0, 0], [0, 1], [0, 2], [1, 3]], 2: [[1, 0], [1, 1], [1, 2], [1, 4]]}) strategy = Strategy(state, 1) assert strategy.which_action_to_take(1) == ((1, 3), (0, 3))
def test_which_action_to_take_multiple_turns(self): board = Board(4, 5, {}, num_of_fish_per_tile=2) state = GameState(board, {1: "black", 2: "white"}, [1, 2], penguin_posns={1: [[0, 0], [0, 1], [0, 2], [1, 3]], 2: [[1, 0], [1, 1], [1, 2], [1, 4]]}) board_tiles = board.get_tiles() board_tiles[0][1] = tile_inst(7) board_tiles[0][2] = tile_inst(12) strategy = Strategy(state, 1) assert strategy.which_action_to_take(2) == ((0, 2), (2, 2))
def approximation(x): strategy = Strategy(init_strategy, vertex_payoff, iters=x, rate=rate, log=False) strategy.FPI() vgs = strategy.vertex_gain.sum() gamma = strategy.gamma return np.log(vgs), np.log(gamma), np.log(gamma / vgs)