public static void Initialise(OptimiserParameters optimiserParameters, StrategyBase strategy)
        {
            _minimumTrades = optimiserParameters.MinimumTrades;
            _maximumTrades = optimiserParameters.MaximumTrades;

            _optimisationType =
                (OptimizationType) Activator.CreateInstance(Type.GetType(optimiserParameters.FitnessFunctionType));
            _optimisationType.Strategy = strategy;
        }
Exemple #2
0
 protected override void OnCalculatePerformanceValue(StrategyBase strategy)
 {
     Value = strategy.SystemPerformance.ShortTrades.TradesPerformance.Percent.Drawdown;
 }
Exemple #3
0
        public void ChangeStrategy(AllegianceInterop.ClientConnection clientConnection, StrategyID strategyID, string playerName, short sideIndex, bool isGameController, bool isCommander)
        {
            //AllegianceInterop.ClientConnection clientConnection;

            //if (_connectedClientsByPlayerName.TryGetValue(playerName, out clientConnection) == false)
            //{
            //    throw new Exception("Couldn't get connection for playerName: " + playerName);
            //}

            //AllegianceInterop.ClientConnection.OnAppMessageDelegate currentStrategyOnAppMessageDelegate;
            //if (_currentStrategyAppMessageDelegateByPlayerName.TryGetValue(playerName, out currentStrategyOnAppMessageDelegate) == true)
            //{
            //    clientConnection.OnAppMessage -= currentStrategyOnAppMessageDelegate;
            //    _currentStrategyAppMessageDelegateByPlayerName.Remove(playerName);
            //}

            StrategyBase currentStrategy;

            if (_currentStrategyByPlayerName.TryGetValue(playerName, out currentStrategy) == false)
            {
                currentStrategy = null;
            }
            else
            {
                //currentStrategy.OnStrategyComplete -= Strategy_OnStrategyComplete;
                _currentStrategyByPlayerName.Remove(playerName);
            }

            StrategyBase strategy = StrategyBase.GetInstance(strategyID, clientConnection, _gameInfo, _botAuthenticationGuid, playerName, sideIndex, isGameController, isCommander);

            strategy.OnStrategyComplete += Strategy_OnStrategyComplete;
            strategy.OnGameComplete     += Strategy_OnGameComplete;


            //StrategyBase strategy = _assemblyLoader.CreateInstance(strategyID);

            //strategy.Attach(clientConnection, _gameInfos[sideIndex], _botAuthenticationGuid, playerName, sideIndex, isGameController, isCommander);



            // Can't hook the transparent object directly to the client, the events raised by c++/cli won't trigger on the managed end
            // becuase they are attached to a copy of the object in the far application domain, so we will attach to the event on the
            // near application domain, then directly call the MessageReceiver handler in the far domain passing the byte array
            // through instead of the tranparent proxied object.
            //AllegianceInterop.ClientConnection.OnAppMessageDelegate onAppMessageDelegate = new AllegianceInterop.ClientConnection.OnAppMessageDelegate((AllegianceInterop.ClientConnection messageClientConnection, byte[] bytes) =>
            //    {
            //        strategy.OnAppMessage(bytes);
            //    });

            //    clientConnection.OnAppMessage += onAppMessageDelegate;

            //    _currentStrategyAppMessageDelegateByPlayerName.Add(playerName, onAppMessageDelegate);
            //    _currentStrategyByPlayerName.Add(playerName, strategy);


            //}
            //else
            //{
            //    throw new Exception($"Error, couldn't find the {strategyID.ToString()} strategy in the loaded strategy list.");
            //}
        }
Exemple #4
0
 public StrategyChromosomeTypeFactory(StrategyBase strategy)
 {
     _parameters = strategy.Parameters;
 }
Exemple #5
0
 protected override void OnCalculatePerformanceValue(StrategyBase strategy)
 {
     Value = 1.0 - strategy.SystemPerformance.AllTrades.TradesPerformance.Percent.AverageMae;
 }
Exemple #6
0
 public StrategyItem(StrategyBase s)
 {
     _s = s;
 }
Exemple #7
0
 protected override void OnCalculatePerformanceValue(StrategyBase strategy)
 {
     Value = strategy.SystemPerformance.LongTrades.TradesPerformance.Percent.AverageProfit;
 }
        private void biSimulation_ItemClick(object sender, ItemClickEventArgs e)
        {
            Stopped = false;
            StrategyBase strategy = (StrategyBase)this.gridView1.GetFocusedRow();

            if (strategy == null)
            {
                XtraMessageBox.Show("No strategy selected.");
                return;
            }
            if (!strategy.SupportSimulation)
            {
                XtraMessageBox.Show("This strategy does not support simulation.");
                return;
            }

            StrategiesManager manager = new StrategiesManager();

            manager.FileName = "SimulationStrategiesManager.xml";
            StrategyBase cloned = strategy.Clone();

            cloned.DemoMode = true;
            manager.Strategies.Add(cloned);

            this.siStatus.Caption = "<b>Loading data from exchanges...</b>";
            IOverlaySplashScreenHandle handle = SplashScreenManager.ShowOverlayForm(gridControl1);

            Application.DoEvents();
            SimulationStrategyDataProvider dataProvider = new SimulationStrategyDataProvider();

            dataProvider.DownloadProgressChanged += OnSimulationProviderDownloadProgressChanged;

            this.beSimulationProgress.EditValue  = 0;
            this.beSimulationProgress.Visibility = BarItemVisibility.Always;

            manager.Initialize(dataProvider);
            dataProvider.DownloadProgressChanged -= OnSimulationProviderDownloadProgressChanged;
            if (!manager.Start())
            {
                XtraMessageBox.Show("Error starting simulation! Please check log messages");
                return;
            }
            this.beSimulationProgress.EditValue  = 0;
            this.beSimulationProgress.Visibility = BarItemVisibility.Always;
            this.siStatus.Caption = "<b>Running simulation...</b>";
            Application.DoEvents();

            Stopwatch timer = new Stopwatch();

            timer.Start();
            int    elapsedSeconds = 0;
            double progress       = 0;

            while (manager.Running)
            {
                this.beSimulationProgress.EditValue = (int)(dataProvider.SimulationProgress * this.repositoryItemProgressBar1.Maximum);
                if (timer.ElapsedMilliseconds / 1000 > elapsedSeconds)
                {
                    elapsedSeconds        = (int)(timer.ElapsedMilliseconds / 1000);
                    this.siStatus.Caption = string.Format("<b>Running simulation... {0} sec</b>", elapsedSeconds);
                    Application.DoEvents();
                }
                if ((dataProvider.SimulationProgress - progress) >= 0.05)
                {
                    progress = dataProvider.SimulationProgress;
                    Application.DoEvents();
                }
            }
            this.beSimulationProgress.Visibility = BarItemVisibility.Never;
            SplashScreenManager.CloseOverlayForm(handle);
            manager.Save();
            this.siStatus.Caption = "<b>Simulation done.</b>";
            Application.DoEvents();
            //this.toastNotificationsManager1.ShowNotification("404ef86f-183c-4fea-960b-86f54e52ea76");
            StrategyConfigurationManager.Default.ShowData(cloned);
        }
		public StrategyEventArgs(string folder, StrategyBase.Strategy strategy, string scriptContextName)
			: this(folder, strategy) {
			this.scriptContextName = scriptContextName;
		}
        private void DoTest(StrategyBase strategy)
        {
            ContextObj context = new ContextObj(strategy);

            context.Request();
        }
 /// <summary>
 /// Adds a strategy to this bot
 /// </summary>
 /// <param name="strat"></param>
 public void AddStrategy(StrategyBase strat)
 {
     _strategies.Add(strat);
 }
 public void Calc(StrategyBase straetgyBase)
 {
     straetgyBase.Calculate();
 }
Exemple #13
0
 public abstract void Set(StrategyBase strategy, ParameterCollection parameterCollection, int idx);
        /// <summary>
        /// return
        /// </summary>
        public StrategySetterWindow(StrategyBase strategy)
        {
            InitializeComponent();

            _StrategyPropertyGrid.DataContext = strategy;
        }
Exemple #15
0
        public FitnessEvaluator(StrategyBase strategy, IList<BaseChromosomeType> chromosomeTypes)
        {
            _strategy = strategy;

            InitialiseStrategyParameterIndices(chromosomeTypes);
        }
 protected override void OnCalculatePerformanceValue(StrategyBase strategy)
 {
     Value = strategy.SystemPerformance.ShortTrades.TradesPerformance.MonthlyUlcer;
 }
Exemple #17
0
        private void UpdateFXCandles(object obj)
        {
            if (_updatingCandles) return;
            if (string.IsNullOrEmpty(_uiService.SelectedStrategyFilename))
            {
                MessageBox.Show("Select strategy to update candles");
                return;
            }

            var strategyType = StrategyHelper.CompileStrategy(_uiService.SelectedCodeText);
            if (strategyType == null)
            {
                MessageBox.Show("Unable to compile strategy");
                return;
            }

            var strategy = (StrategyBase)Activator.CreateInstance(strategyType);

            _updatingCandles = true;
            var dispatcher = Dispatcher.CurrentDispatcher;
            var fxcm = _brokersService.Brokers.First(x => x.Name == "FXCM");
            var timeframes = strategy.Timeframes.Union(new[] { Timeframe.M1 }).ToArray();
            var markets = strategy.Markets;

            if (markets == null)
            {
                markets = StrategyBase.GetDefaultMarkets();
            }

            var view = new ProgressView { Owner = Application.Current.MainWindow };
            view.TextToShow.Text = "Updating candles";

            Task.Run(() =>
            {
                try
                {
                    CandlesHelper.UpdateCandles(
                        fxcm,
                        _candleService,
                        markets,
                        timeframes,
                        updateProgressAction: s =>
                        {
                            _dispatcher.BeginInvoke((Action)(() =>
                           {
                               view.TextToShow.Text = s;
                           }));
                        });
                }
                catch (Exception ex)
                {
                    Log.Error("Unable to update candles", ex);
                }

                dispatcher.Invoke(() =>
                {
                    view.Close();
                    MessageBox.Show("Updating candles complete");
                    _updatingCandles = false;
                });
            });

            view.ShowDialog();
        }
Exemple #18
0
 public abstract void WriteValue(StrategyBase strategy, ParameterCollection rgParams, int iValue);
        private void biOptimizeParams_ItemClick(object sender, ItemClickEventArgs e)
        {
            Stopped = false;
            StrategyBase strategy = (StrategyBase)this.gridView1.GetFocusedRow();

            if (strategy == null)
            {
                XtraMessageBox.Show("No strategy selected.");
                return;
            }

            if (!strategy.SupportSimulation)
            {
                XtraMessageBox.Show("This strategy does not support simulation.");
                return;
            }

            using (ParamsConfigurationForm form = new ParamsConfigurationForm()) {
                form.Strategy = strategy;
                if (form.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
            }

            this.siStatus.Caption = "<b>Loading data from exchanges...</b>";
            //IOverlaySplashScreenHandle handle = SplashScreenManager.ShowOverlayForm(gridControl1);
            Application.DoEvents();

            this.beSimulationProgress.EditValue  = 0;
            this.beSimulationProgress.Visibility = BarItemVisibility.Always;

            StrategyOptimizationManager optManager = new StrategyOptimizationManager(strategy);

            CurrentOpimizationManager = optManager;
            //NSGAII algorithm = new NSGAII(optManager);
            SimpleOptimizationAlgorithm algorithm = new SimpleOptimizationAlgorithm(optManager);

            CurrentAlgorithm  = algorithm;
            optManager.Error += (d, ee) => {
                XtraMessageBox.Show("Error cannot initialize strategies manager");
                throw new Exception("Error");
            };

            optManager.StateChanged += (d, ee) => {
                this.siStatus.Caption = optManager.State;
                this.beSimulationProgress.EditValue = (int)(optManager.SimulationProgress * this.repositoryItemProgressBar1.Maximum);
                Application.DoEvents();
            };

            algorithm.Initialize();

            while (!Stopped && !algorithm.IsTerminated)
            {
                algorithm.Evolve();
            }
            //SplashScreenManager.CloseOverlayForm(handle);
            this.beSimulationProgress.Visibility = BarItemVisibility.Never;
            this.siStatus.Caption = "<b>Optimization done.</b>";
            Application.DoEvents();
            CurrentOpimizationManager = null;
            CurrentAlgorithm          = null;
        }
    public static double Caculate(StrategyBase stra)
    {
        double tm = stra.Caculate();

        return(tm);
    }
 /// <summary>
 /// AddStrategyNode
 /// </summary>
 /// <param name="strategy"></param>
 private void AddStrategyNode(StrategyBase strategy)
 {
     checkedListBoxStrategies.Items.Add(strategy);
 }
Exemple #22
0
 protected override void OnCalculatePerformanceValue(StrategyBase strategy)
 {
     Value = strategy.SystemPerformance.LongTrades.TradesPerformance.SortinoRatio;
 }
Exemple #23
0
 protected override void OnCalculatePerformanceValue(StrategyBase strategy)
 {
     Value = strategy.SystemPerformance.AllTrades.TradesPerformance.Probability;
 }
 /// <summary>
 /// StrategyEventArgs
 /// </summary>
 /// <param name="strategy">event args</param>
 public StrategyEventArgs(StrategyBase strategy)
 {
     Strategy = strategy;
 }
Exemple #25
0
 protected override void OnCalculatePerformanceValue(StrategyBase strategy)
 {
     Value = strategy.SystemPerformance.LongTrades.TradesPerformance.GrossProfit + strategy.SystemPerformance.LongTrades.TradesPerformance.GrossLoss;
 }
Exemple #26
0
        /// <summary>
        /// Execute une strategie
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="context">The context.</param>
        /// <param name="strategy">The strategy.</param>
        private static void RunStrategy(ICustomizableElement element, GenerationContext context, StrategyBase strategy)
        {
            ILogger logger = ServiceLocator.Instance.GetService <ILogger>();

            if (logger != null)
            {
                logger.Write("Running strategy", String.Concat("Strategy '", strategy.DisplayName, "' id : ", strategy.StrategyId), LogType.Debug);
            }
            if (context.SelectedStrategies != null && (context.SelectedStrategies != null && !context.SelectedStrategies.Contains(strategy)))
            {
                if (logger != null)
                {
                    logger.Write("Running strategy", "Strategy skipped because this is not a selected strategy", LogType.Debug);
                }
            }
            else if (context.CanGenerate(element.Id))
            {
                RunStrategyInternal(element, strategy, context);
            }
        }
Exemple #27
0
        //public void LoadStrategies()
        //{
        //    // To load strategies into the current app domain without using transparent proxy, you can uncomment this, but it
        //    // will break dynamic strategy updates.
        //    //
        //    //_currentAppDomain = AppDomain.CurrentDomain;
        //    //string target = Path.Combine(_currentAppDomain.BaseDirectory, "Strategies.dll");
        //    //_assemblyLoader = new AssemblyLoader(target);
        //    //return;

        //    // Load strategies into a separate app domain so that they can be hot-swapped while a game is running.
        //    var an = Assembly.GetExecutingAssembly().GetName();

        //    var appDomainSetup = new AppDomainSetup
        //    {
        //        PrivateBinPath = AppDomain.CurrentDomain.BaseDirectory,
        //        ShadowCopyDirectories = AppDomain.CurrentDomain.BaseDirectory,
        //        ShadowCopyFiles = "true"
        //    };

        //    _currentAppDomain = AppDomain.CreateDomain("V1", (Evidence)null, appDomainSetup);

        //    //Console.WriteLine(_currentAppDomain.BaseDirectory);

        //    _currentAppDomain.Load(typeof(AssemblyLoader).Assembly.FullName);

        //    string target = Path.Combine(_currentAppDomain.BaseDirectory, "Strategies.dll");

        //    _assemblyLoader = (AssemblyLoader)Activator.CreateInstance(
        //        _currentAppDomain,
        //        typeof(AssemblyLoader).Assembly.FullName,
        //        typeof(AssemblyLoader).FullName,
        //        false,
        //        BindingFlags.Public | BindingFlags.Instance,
        //        null,
        //        new object[] { target },
        //        null,
        //        null).Unwrap();
        //}

        public void ChangeStrategy(AllegianceInterop.ClientConnection clientConnection, StrategyID strategyID, StrategyBase lastStrategy)
        {
            ChangeStrategy(clientConnection, strategyID, lastStrategy.PlayerName, lastStrategy.SideIndex, lastStrategy.IsGameController, lastStrategy.IsCommander);
        }
Exemple #28
0
 protected override void OnCalculatePerformanceValue(StrategyBase strategy)
 {
     Value = strategy.SystemPerformance.LongTrades.TradesPerformance.ProfitFactor;
 }
Exemple #29
0
        private void Strategy_OnGameComplete(StrategyBase strategy)
        {
            Log(strategy.PlayerName, $"OnGameComplete: Exiting WOPR to trigger a new game to start.");

            _cancellationTokenSource.Cancel();
        }
 public ExceptionRule(PublisherList publisherList, StrategyBase strategyBase)
 {
     _publisherList = publisherList;
     _strategyBase  = strategyBase;
 }
        public static void StrategyHandleClickedButton(StrategyBase strategy, ClickhandlerArgs cha, Queue <SingleSpread> spreads, string strratio, LegEntryType leg1entrytype, LegEntryType leg2entrytype, object ieh)
        {
            int _units = cha.Units;

            //  bool b= mut.WaitOne(new TimeSpan(0,0,3));
            // if (b == false) throw new TimeoutException("clickcustomhandler mutex timeout");
            switch (cha.ClickedButton)
            {
            case ClickedButton.Close:
                lock (spreads){
                    foreach (SingleSpread spread in spreads)
                    {
                        spread.Exit(LegExitType.Market, LegExitType.Market);
                    }
                }
                break;

            case ClickedButton.Reverse:
                lock (spreads){
                    foreach (SingleSpread s in spreads)
                    {
                        s.Reverse();
                    }
                }
                break;

            case ClickedButton.GoLong:
                lock (spreads){
                    foreach (SingleSpread s in spreads)
                    {
                        if (s.MarketPosition != MarketPosition.Long)
                        {
                            Zweistein.NinjaTraderLog.Process("GoLong: already Short", "", LogLevel.Error, LogCategories.User);
                            if (strategy.TraceOrders)
                            {
                                strategy.Print("GoLong: already Short");
                            }
                            return;
                        }
                    }
                    //strategy.Account.Currency
                    SingleSpread spread = new SingleSpread(MarketPosition.Long, _units, strratio, strategy);

                    spread.Entry(leg1entrytype, leg2entrytype);
                    IExitHandling eh = ieh as IExitHandling;
                    spread.setIExitHandling(eh);
                    if (cha.Guid != null)
                    {
                        spread.Guid = cha.Guid;
                    }

                    spreads.Enqueue(spread);
                }
                break;

            case ClickedButton.GoShort:
                lock (spreads){
                    foreach (SingleSpread s in spreads)
                    {
                        if (s.MarketPosition != MarketPosition.Short)
                        {
                            Zweistein.NinjaTraderLog.Process("GoShort: already Long", "", LogLevel.Error, LogCategories.User);
                            if (strategy.TraceOrders)
                            {
                                strategy.Print("GoShort: already Long");
                            }
                            return;
                        }
                    }
                    SingleSpread spread = new SingleSpread(MarketPosition.Short, _units, strratio, strategy);
                    spread.Entry(leg1entrytype, leg2entrytype);
                    IExitHandling eh = ieh as IExitHandling;
                    spread.setIExitHandling(eh);
                    if (cha.Guid != null)
                    {
                        spread.Guid = cha.Guid;
                    }
                    spreads.Enqueue(spread);
                }
                break;
            }
        }
Exemple #32
0
 protected override void OnCalculatePerformanceValue(StrategyBase strategy)
 {
     Value = strategy.SystemPerformance.LongTrades.TradesPerformance.RSquared;
 }
Exemple #33
0
 protected override void OnCalculatePerformanceValue(StrategyBase strategy)
 {
     Value = strategy.SystemPerformance.AllTrades.TradesPerformance.SharpeRatio;
 }
 public StrategyChromosomeTypeFactory(StrategyBase strategy)
 {
     _parameters = strategy.Parameters;
 }