コード例 #1
0
def start_ui():
    board = Board(6, 6)
    strategy = Strategy()
    p1 = Human('x', board)
    p2 = Computer("0", board, strategy)
    minimax = Minimax()
    game = Game(p1, p2, board, minimax)
    game.start()
コード例 #2
0
def start_gui():
    board = GuiBoard(9, 9)
    strategy = Strategy()
    p1 = GuiHuman('x', board)
    p2 = Computer('0', board, strategy)
    game = GuiGame(p1, p2, board)
    root = tkinter.Tk()
    my_gui = Gui(root, game)
    root.mainloop()
コード例 #3
0
ファイル: bot.py プロジェクト: maximepeter/trading_project
    def run(self, date, strategy_name, log):
        """
        Run strategy and update wallet 
        """

        if self.stocks[0].getDateValue(date):
            if strategy_name == "naive":
                strategy = StrategyNaive(
                    self.stocks, date, self.initial_account, self.lower, self.upper)
            else:
                strategy = Strategy(self.stocks, date, 1000, 0.7, 0.3)
            strats = strategy.run()

            self.wallet.save_last_account()

            for i, strat in enumerate(strats):
                # if the strategie says "buy" and the amount is available
                if strat[0] == "buy" and strat[1] > 0 and self.wallet.buying_autorisation(i, strat[1], date):
                    if log:
                        print(
                            "Buy " + str(strat[1]) + " stock(s) of " + self.stocks[i].getName())
                    self.wallet.buy(i, date, int(strat[1]))
                    self.stocks[i].buy(
                        int(strat[1]), self.stocks[i].getDateValue(date))

                # if the strategie says "sell"
                elif strat[0] == "sell" and self.stocks[i].getQuantity() > 0 and strat[1] > 0:

                    sell = self.stocks[i].sell(int(strat[1]))
                    if sell is not None:
                        self.wallet.sell(i, date)
                        if log:
                            print(
                                "Sell " + str(self.stocks[i].getQuantity()) + " stock(s) of " + self.stocks[i].getName())

                else:
                    if log:
                        print("No go")

            self.wallet.update(date)

            self.last_account = self.wallet.virtual_account
            self.total_commission = self.wallet.total_commission
            self.total_transaction = self.wallet.total_transaction

            if log:
                print("Date : ", date, "Wallet account : ", self.wallet.virtual_account, ", Stocks amount : ", self.wallet.stocks_amount, ", Available cash : ", self.wallet.available_cash, "\nVariation with previous day : ",
                      int(10000*(self.wallet.virtual_account-self.wallet.last_account)/self.wallet.virtual_account)/100)
コード例 #4
0
ファイル: main.py プロジェクト: nmakeenkov/junction_2k16
def main():
    pygame.init()
 
    # Set the width and height of the screen [width, height]
    size = (int(settings.WIDTH * ZOOM), int(settings.HEIGHT * ZOOM))
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Simulator")

    royal_manager = RoyalManager()
    room = royal_manager.room
    strategy = Strategy(room)
    done = False
    clock = pygame.time.Clock()
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
        strategy.run_tick()
        royal_manager.run_simulation_tick()
        Serializer.serialize(room, screen)
        clock.tick(60)
コード例 #5
0
 def __init__(self):
     IDABot.__init__(self)
     self.workers = []
     self.building_manager = BuildingManager(self)
     self.resource_manager = ResourceManager(self.minerals, self.gas,
                                             self.current_supply, self)
     self.unit_manager = UnitManager(self)
     self.strategy_network = Strategy(self)
     self.assignment_manager = AssignmentManager(self)
     self.scout_manager = ScoutingManager(self)
     self.building_strategy = BuildingStrategy(self, self.resource_manager,
                                               self.assignment_manager)
     self.print_debug = PrintDebug(self, self.building_manager,
                                   self.unit_manager, self.scout_manager,
                                   self.building_strategy, True)
     self.first = True
     self.counter = 0
     self.left = True
     self.dance = 0
     # Last time that strategy was handled by generating tasks etc
     self.last_handled_strategy = 0
コード例 #6
0
    def run(self, date, strategy_name, log):
        """
        Run strategy and update wallet 
        """

        if log:
            print("\nOpen : \nWallet account : " +
                  str(self.wallet.virtual_account) + "\nStocks amount : " +
                  str(self.wallet.stocks_amount) + "\nAvailable cash : " +
                  str(self.wallet.available_cash) + "\n")

        if self.stocks[0].getDateValue(date):
            if strategy_name == "naive":
                strategy = StrategyNaive(self.stocks, date,
                                         self.initial_account, self.lower,
                                         self.upper)
            elif strategy_name == "ml":
                strategy = StrategyML(self.stocks, date, 3000)
            else:
                strategy = Strategy(self.stocks, date, 1000, 0.7, 0.3,
                                    self.wallet.available_cash)
            strats = strategy.run()

            self.wallet.save_last_account()

            for i, strat in enumerate(strats):
                # if the strategie says "buy" and the amount is available
                stock = self.stocks[i]
                if strat[0] == "buy" and strat[
                        1] > 0 and self.wallet.buying_autorisation(
                            i, strat[1], date):
                    stock.buy(int(strat[1]), self.wallet,
                              stock.getDateValue(date))
                    if log:
                        print(stock.getName() + " (" +
                              str(stock.getQuantity()) + "|" +
                              str(stock.getDateValue(date)) + ")" + " : Buy " +
                              str(strat[1]) + " stock(s)" + " -> +" +
                              str(strat[1] * stock.getDateValue(date)) +
                              " euros")

                # if the strategie says "sell"
                elif strat[0] == "sell" and stock.getQuantity(
                ) > 0 and strat[1] > 0:
                    sell = stock.sell(self.wallet,
                                      stock.getDateValue(date),
                                      quantity=int(strat[1]))
                    if sell is not None:
                        if log:
                            print(stock.getName() + " (" +
                                  str(stock.getQuantity()) + "|" +
                                  str(stock.getDateValue(date)) + ")" +
                                  " : Sell " + str(strat[1]) + " stock(s)" +
                                  " -> -" +
                                  str(strat[1] * stock.getDateValue(date)) +
                                  " euros")

                else:
                    if log:
                        print(stock.getName() + " (" +
                              str(stock.getQuantity()) + "|" +
                              str(stock.getDateValue(date)) + ")" + " : No go")

            self.wallet.update(date)

            self.last_account = self.wallet.virtual_account
            self.total_commission = self.wallet.total_commission
            self.total_transaction = self.wallet.total_transaction

            if log:
                print("\nClose : \nWallet account : " +
                      str(self.wallet.virtual_account) + "\nStocks amount : " +
                      str(self.wallet.stocks_amount) + "\nAvailable cash : " +
                      str(self.wallet.available_cash) +
                      "\nVariation with previous day : " +
                      str(100 * ((self.wallet.virtual_account -
                                  self.wallet.last_account) /
                                 self.wallet.virtual_account)) + "\n")
コード例 #7
0
ファイル: master.py プロジェクト: phroiland/FinBiotic
def main():
    print "------ System online -------", datetime.now()

    parser = argparse.ArgumentParser()

    common.config.add_argument(parser)

    parser.add_argument('--instrument',
                        "-i",
                        type=common.args.instrument,
                        required=True,
                        action="append",
                        help="Instrument to get prices for")

    parser.add_argument('--snapshot',
                        action="store_true",
                        default=True,
                        help="Request an initial snapshot")

    parser.add_argument('--no-snapshot',
                        dest="snapshot",
                        action="store_false",
                        help="Do not request an initial snapshot")

    parser.add_argument('--show-heartbeats',
                        "-s",
                        action='store_true',
                        default=False,
                        help="display heartbeats")

    args = parser.parse_args()
    # print sys.argv[2]
    account_id = args.config.active_account
    api = args.config.create_streaming_context()
    account_api = args.config.create_context()

    response = api.pricing.stream(account_id,
                                  snapshot=args.snapshot,
                                  instruments=",".join(args.instrument))

    dfD = PivotImports(sys.argv[2]).daily()
    # dfW = p.weekly()
    balance = Balance(account_api, account_id).balance()

    df = pd.DataFrame([])

    for msg_type, msg in response.parts():
        if msg_type == "pricing.Heartbeat" and args.show_heartbeats:
            print heartbeat_to_string(msg)

        if msg_type == "pricing.Price":
            sd = StreamingData(datetime.now(), instrument_string(msg),
                               mid_string(msg), account_api, account_id, 's',
                               '5min', balance)
            df = df.append(sd.df())
            sd.resample(df)
            print "df:", df.shape[0], "minuteData:", sd.minuteData().shape[0]
            # print sd.minuteData(),'\n'

            if sd.minuteData().shape[0] < 20:
                continue

            else:
                client = oandapyV20.API(settings.ACCESS_TOKEN)
                r = openPos.OpenPositions(accountID=account_id)
                client.request(r)
                openTrades = []
                for i in r.response['positions']:
                    trades = i['instrument']
                    openTrades.append(trades)
                print 'Open Trades', openTrades

                if instrument_string(msg) in openTrades:
                    continue

                else:
                    try:
                        b = Breakout(sd.minuteData())
                        breakout = b.breakout()
                        # print 'Breakout Units:',breakout

                        s = Spreads(dfD, mid_string(msg))
                        pivot, rl1, rl2, rl3, sl1, sl2, sl3 = s.spreads()
                        rate1, rate2 = s.spreads_out()

                        strat = Strategy(account_api, account_id,
                                         instrument_string(msg), dfD,
                                         mid_string(msg), breakout, pivot, rl1,
                                         rl2, rl3, sl1, sl2, sl3, rate1, rate2)
                        strat.res_check()
                        strat.sup_check()

                    except Exception as e:
                        print e
コード例 #8
0
ファイル: master.py プロジェクト: phroiland/FinBiotic
def main():
    print "------ System online -------", datetime.now()

    parser = argparse.ArgumentParser()

    common.config.add_argument(parser)

    parser.add_argument('--instrument', "-i", type=common.args.instrument,
                        required=True, action="append",
                        help="Instrument to get prices for")

    parser.add_argument('--snapshot', action="store_true", default=True,
                        help="Request an initial snapshot")

    parser.add_argument('--no-snapshot', dest="snapshot", action="store_false",
                        help="Do not request an initial snapshot")

    parser.add_argument('--show-heartbeats', "-s", action='store_true',
                        default=False, help="display heartbeats")

    args = parser.parse_args()
    account_id = args.config.active_account
    api = args.config.create_streaming_context()
    account_api = args.config.create_context()

    response = api.pricing.stream(account_id, snapshot=args.snapshot,
                                  instruments=",".join(args.instrument))

    dfD = PivotImports(sys.argv[2]).daily()
    # dfW = p.weekly()
    balance = Balance(account_api, account_id).balance()

    df = pd.DataFrame([])

    for msg_type, msg in response.parts():
        if msg_type == 'pricing.Heartbeat' and args.show_heartbeats:
            print(heartbeat_to_string(msg))

        if msg_type == "pricing.Price":
            sd = StreamingData(datetime.now(), instrument_string(msg),
                               mid_string(msg), account_api, account_id, 's',
                               '1min', balance)
            df = df.append(sd.df())
            '''
                Re-sample is based on time parameter set in StreamingData().
                i.e., 1min, 5min, 15min, etc.
            '''
            sd.resample(df)

            '''
                This following output is information on the streaming data that has been collected.
                    df.shape[0]: represents the current/cumulative rows of streaming data that has come in.
                    sd.shape[0]: represents the current/cumulative rows related to the time frame being evaluated.
            '''
            # print "df:", df.shape[0], "minuteData:", sd.minuteData().shape[0]
            print sd.minuteData(), '\n'

            if sd.minuteData().shape[0] < 20:
                continue
            else:
                client = oandapyV20.API(settings.ACCESS_TOKEN)
                r = openPos.OpenPositions(accountID=account_id)
                client.request(r)

                '''
                    Declare array to store open trades so multiple positions aren't established on a single currency.
                '''
                openTrades = []
                for i in r.response['positions']:
                    trades = i['instrument']
                    openTrades.append(trades)
                print('Open Trades', openTrades)

                if instrument_string(msg) in openTrades:
                    continue
                else:
                    try:
                        breakout = Breakout(sd.minuteData(), mid_string(msg))
                        breakout_units = breakout.breakout()
                        if breakout_units is None:
                            pass
                        else:
                            spread = Spreads(dfD, mid_string(msg))
                            pivot, rl1, rl2, rl3, sl1, sl2, sl3 = spread.spreads()
                            rate1, rate2 = spread.spreadRates()
                            strategy = Strategy(
                                instrument_string(msg), dfD, mid_string(msg), breakout_units,
                                pivot, rl1, rl2, rl3, sl1, sl2, sl3, rate1, rate2
                            )

                            if strategy.resistance_check() is None:
                                continue
                            else:
                                units, stop_loss, profit = strategy.resistance_check()
                                try:
                                    resistance_execute = Execute(
                                        account_api, account_id, instrument_string(msg), units, stop_loss, profit
                                    )
                                    resistance_execute.trade()
                                except Exception as e:
                                    print(e)

                            if strategy.support_check() is None:
                                continue
                            else:
                                units, stop_loss, profit = strategy.support_check()
                                try:
                                    support_execute = Execute(
                                        account_api, account_id, instrument_string(msg), units, stop_loss, profit
                                    )
                                    support_execute.trade()
                                except Exception as e:
                                    print(e)

                    except Exception as e:
                        print(e)
コード例 #9
0
    def __init__(self):
        IDABot.__init__(self)
        self.minerals_in_base = {}
        self.building_manager = BuildingManager(self)
        self.resource_manager = ResourceManager(self.minerals, self.gas,
                                                self.current_supply, self)
        self.unit_manager = UnitManager(self)
        self.strategy_network = Strategy(self)
        self.assignment_manager = AssignmentManager(self)
        self.scout_manager = ScoutingManager(self)
        self.building_strategy = BuildingStrategy(self, self.resource_manager,
                                                  self.assignment_manager)
        self.print_debug = PrintDebug(self, self.building_manager,
                                      self.unit_manager, self.scout_manager,
                                      self.building_strategy, True)
        self.our_building_placer = None
        # Last time that strategy was handled by generating tasks etc
        self.last_handled_strategy = 0
        self.first_tick = True
        self.block = False
        self.base_right = None
        self.choke_points_right = {
            (24.25, 28.5): Point2D(57, 73),
            (56.25, 130.5): Point2D(53, 118),
            (58.75, 99.0): Point2D(47, 92),
            (129.25, 54.5): Point2D(113, 58),
            (63.75, 51.0): Point2D(57, 73),
            (93.25, 69.0): Point2D(76, 84),
            (88.25, 117.0): Point2D(73, 115),
            (92.5, 143.5): Point2D(77, 134),
            (26.5, 137.5): Point2D(30, 133),
            (22.75, 113.5): Point2D(31, 118),
            (59.5, 24.5): Point2D(57, 73),
            (95.75, 37.5): Point2D(88, 49),
            (24.25, 83.5): Point2D(44, 95),
            (127.75, 139.5): Point2D(115, 135),
            (127.75, 84.5): Point2D(76, 84),
            (127.75, 28.5): Point2D(116, 44)
        }

        self.choke_points_left = {
            (58.75, 99.0): Point2D(58, 80),
            (24.25, 139.5): Point2D(36, 124),
            (127.75, 139.5): Point2D(95, 90),
            (92.5, 143.5): Point2D(95, 90),
            (56.25, 130.5): Point2D(64, 120),
            (22.75, 113.5): Point2D(38, 110),
            (127.75, 84.5): Point2D(113, 77),
            (24.25, 28.5): Point2D(37, 32),
            (24.25, 83.5): Point2D(58, 80),
            (88.25, 117.0): Point2D(76, 84),
            (93.25, 69.0): Point2D(108, 71),
            (59.5, 24.5): Point2D(71, 31),
            (95.75, 37.5): Point2D(98, 49),
            (63.75, 51.0): Point2D(79, 53),
            (129.25, 54.5): Point2D(121, 50),
            (127.75, 28.5): Point2D(117, 37)
        }

        self.messages = [
            "We estimate the probability of winning to be over 95%",
            "Eslöööööööv"
        ]
コード例 #10
0
 def strategy(self):
     if not self._strategy:
         self._strategy = Strategy()
     return self._strategy