示例#1
0
        public override void Run()
        {
            MulticoreOptimizer optimizer = new MulticoreOptimizer();

            OptimizationUniverse universe = new OptimizationUniverse();

            for (int length1 = 2; length1 < 14; length1++)
            {
                for (int length2 = length1 + 1; length2 < 28; length2++)
                {
                    OptimizationParameterSet parameter = new OptimizationParameterSet();

                    parameter.Add("Length1", length1);
                    parameter.Add("Length2", length2);
                    parameter.Add("Bar", (long)60);

                    universe.Add(parameter);
                }
            }

            strategy = new SMACrossover(framework, "strategy ");

            Instrument instrument1 = InstrumentManager.Instruments["AAPL"];
            Instrument instrument2 = InstrumentManager.Instruments["MSFT"];

            InstrumentList instruments = new InstrumentList();

            instruments.Add(instrument1);
            instruments.Add(instrument2);

            DataSimulator.DateTime1 = new DateTime(2013, 12, 01);
            DataSimulator.DateTime2 = new DateTime(2013, 12, 31);

            optimizer.Optimize(strategy, instruments, universe, 100);
        }
        public void LoadTest()
        {
            InstrumentList instruments = new InstrumentList();

            instruments.Load();
            Assert.AreEqual(6, instruments.Count);
        }
 void Delete()
 {
     if (CurrentInstrument != null && InstrumentList.Contains(CurrentInstrument))
     {
         InstrumentList.Remove(CurrentInstrument);
     }
 }
示例#4
0
        public override IEnumerable <Quote> GetQuoteList(string accountId, string mode)
        {
            //This need to be changed to PRICE API
            //TODO *******************************************************


            List <TDMData> instrList = null;
            List <Quote>   result    = new List <Quote>();
            Quote          q         = null;

            string[] tickerList = this.GetTickerList();
            for (int i = 0; i < tickerList.Length; i++)
            {
                instrList = GetInstrumentList(tickerList[i]);
                if (instrList == null)
                {
                    instrList = GetSymbolPriceList(tickerList[i], (DateTime.Now.AddDays(-5)));
                    InstrumentList.Add(tickerList[i], instrList);
                }
                q        = new Quote();
                q.Symbol = tickerList[i];
                if (mode == Constants.OrderAction.BUY)
                {
                    q.LastBuyTradePrice = GetCurrentBuyPrice(q.Symbol);
                }
                else if (mode == Constants.OrderAction.SELL)
                {
                    q.LastSellTradePrice = GetCurrentSellPrice(q.Symbol);
                }

                result.Add(q);
            }
            return(result);
        }
        public void UpdateTest()
        {
            //Load up Guids
            PerformerList performers = new PerformerList();
            Performer     performer  = new Performer();

            performers.Load();
            performer = performers.FirstOrDefault(p => p.FirstName == "Hunter");

            GroupList groups = new GroupList();
            Group     group  = new Group();

            groups.Load();
            group = groups.FirstOrDefault(c => c.Name == "Jazz Ensemble");

            InstrumentList instruments = new InstrumentList();
            Instrument     instrument  = new Instrument();

            instruments.Load();
            instrument = instruments.FirstOrDefault(c => c.Description == "Euphonium");

            GroupMember     groupMember  = new GroupMember();
            GroupMemberList groupMembers = new GroupMemberList();

            groupMembers.Load();
            groupMember           = groupMembers.FirstOrDefault(p => p.GroupId == group.Id && p.PerformerId == performer.Id);
            groupMember.StartDate = Convert.ToDateTime("04/24/3000");
            groupMember.EndDate   = Convert.ToDateTime("04/25/3000");

            groupMember.Instrument = instrument.Id;
            int results = groupMember.Update();

            Assert.IsTrue(results == 1);
        }
示例#6
0
        private void ctxPanel_Remove_Click(object sender, EventArgs e)
        {
            InstrumentList instrumentList = new InstrumentList();

            foreach (InstrumentRow instrumentRow in (BaseCollection)this.dgvPanel.SelectedRows)
            {
                instrumentList.Add(instrumentRow.Instrument);
            }
            if (((FIXGroupList)instrumentList).Count <= 0 || MessageBox.Show("Do you want to remove selected instruments?", "Remove", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
            {
                return;
            }
            IEnumerator enumerator = ((FIXGroupList)instrumentList).GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    this.RemoveInstrument((Instrument)enumerator.Current);
                }
            }
            finally
            {
                IDisposable disposable = enumerator as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        }
        public void Update()
        {
            InstrumentList instruments = new InstrumentList();

            instruments.Load();
            Instrument instrument          = instruments.FirstOrDefault(ct => ct.Description == "SLTEST");
            Instrument retrievedInstrument = new Instrument();

            if (instrument != null)
            {
                retrievedInstrument.Id = instrument.Id;

                instrument.Description = "SLTEST1";

                //Act
                HttpClient client = InitializeClient();
                //Serialize a question object that we're trying to insert
                string serializedInstrument = JsonConvert.SerializeObject(instrument);
                var    content = new StringContent(serializedInstrument);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                HttpResponseMessage response = client.PutAsync("Instrument/" + instrument.Id, content).Result;

                retrievedInstrument.LoadById();
            }
            //Assert
            Assert.AreEqual(instrument.Description, retrievedInstrument.Description);
        }
 public override void Subscribe(InstrumentList instruments)
 {
     foreach (var item in instruments)
     {
         Subscribe(item);
     }
 }
示例#9
0
 protected StrategyBase(string name, string description)
 {
     this.metaStrategyBase = null;
     this.name             = name;
     this.description      = description;
     this.isEnabled        = true;
     this.isActive         = true;
     this.ReportManager    = (StrategyComponentManager.GetComponent("{5E7810DC-C9C1-427f-8CD9-1DFFE26E59B5}", this) as ReportManager);
     this.MarketManager    = (StrategyComponentManager.GetComponent("{849E4CFE-C19E-4d1e-899D-0BB26DB12AAD}", this) as MarketManager);
     this.portfolio        = PortfolioManager.Portfolios[name];
     if (this.portfolio == null)
     {
         this.portfolio = new Portfolio(name);
     }
     this.tester             = new LiveTester(this.portfolio);
     this.stops              = new StopList();
     this.triggers           = new TriggerList();
     this.marketDataProvider = null;
     this.executionProvider  = null;
     this.newsProvider       = null;
     this.executionService   = null;
     this.orders             = new OrderTable();
     this.global             = new Hashtable();
     this.activeInstruments  = new InstrumentList();
     this.barSliceManager    = new BarSliceManager();
     this.componentTypeList  = new List <ComponentType>();
     this.componentTypeList.Add(ComponentType.MarketManager);
     this.componentTypeList.Add(ComponentType.ReportManager);
     this.activeStops = new Dictionary <Instrument, List <StopBase> >();
     this.portfolios  = new Dictionary <Instrument, Portfolio>();
     this.testers     = new Dictionary <Instrument, LiveTester>();
     this.statisticsPerInstrumentEnabled = false;
 }
示例#10
0
        protected override void OnSubscribe(InstrumentList instruments)
        {
            // Get size of bar.
            barSize = (long)Global[barSizeCode];

            // Get roll info.
            rollInfo = (List <RollInfo>)Global[rollInfoCode];

            // Get root instrument.
            rootInstrument = instruments.GetByIndex(0);

            // Get current futures contract.
            currentFuturesContract = rootInstrument.Legs[legIndex].Instrument;

            // Add current futures contract to bar factory.
            BarFactory.Add(currentFuturesContract, BarType.Time, barSize);

            // Add current futures contract to strategy.
            AddInstrument(currentFuturesContract);

            // Add reminder to maturity date and roll time.
            AddReminder(rollInfo[legIndex].Maturity.Date + TimeOfRoll);

            AddGroups();
        }
        public void Insert()
        {
            //Setup
            Instrument instrument = new Instrument
            {
                Description = "SLTEST"
            };
            InstrumentList instruments = new InstrumentList();

            instruments.Load();
            int originalCount = instruments.Count();



            //Act
            HttpClient client = InitializeClient();
            //Serialize a instrument object that we're trying to insert
            string serializedInstrument = JsonConvert.SerializeObject(instrument);
            var    content = new StringContent(serializedInstrument);

            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            HttpResponseMessage response = client.PostAsync("Instrument", content).Result;

            //Assert
            instruments.Clear();
            instruments.Load();
            Assert.AreEqual(originalCount + 1, instruments.Count);
        }
示例#12
0
 public void Subscribe(IDataProvider provider, InstrumentList instruments)
 {
     if (provider.Status != ProviderStatus.Connected)
     {
         provider.Connect();
     }
     InstrumentList instrumentList = new InstrumentList();
     for (int i = 0; i < instruments.Count; i++)
     {
         Instrument byIndex = instruments.GetByIndex(i);
         if (!this.subscriptions.ContainsKey((int)provider.Id))
         {
             this.subscriptions[(int)provider.Id] = new Dictionary<Instrument, int>();
         }
         if (!this.subscriptions[(int)provider.Id].ContainsKey(byIndex) || this.subscriptions[(int)provider.Id][byIndex] == 0)
         {
             this.subscriptions[(int)provider.Id][byIndex] = 0;
             instrumentList.Add(byIndex);
         }
         Dictionary<Instrument, int> dictionary;
         Instrument key;
         (dictionary = this.subscriptions[(int)provider.Id])[key = byIndex] = dictionary[key] + 1;
     }
     if (instrumentList.Count > 0)
     {
         provider.Subscribe(instrumentList);
     }
 }
        // GET: api/Instrument
        public IEnumerable <Instrument> Get()
        {
            InstrumentList instruments = new InstrumentList();

            instruments.Load();
            return(instruments);
        }
示例#14
0
 protected StrategyBase(string name, string description)
 {
     this.metaStrategyBase = (MetaStrategyBase)null;
     this.name             = name;
     this.description      = description;
     this.isEnabled        = true;
     this.isActive         = true;
     this.ReportManager    = StrategyComponentManager.GetComponent("getcom", (object)this) as ReportManager;
     this.MarketManager    = StrategyComponentManager.GetComponent("getcom", (object)this) as MarketManager;
     this.portfolio        = PortfolioManager.Portfolios[name];
     if (this.portfolio == null)
     {
         this.portfolio = new Portfolio(name);
     }
     this.tester             = new LiveTester(this.portfolio);
     this.stops              = new StopList();
     this.triggers           = new TriggerList();
     this.marketDataProvider = (IMarketDataProvider)null;
     this.executionProvider  = (IExecutionProvider)null;
     this.newsProvider       = (INewsProvider)null;
     this.executionService   = (IExecutionService)null;
     this.orders             = new OrderTable();
     this.global             = new Hashtable();
     this.activeInstruments  = new InstrumentList();
     this.barSliceManager    = new BarSliceManager();
     this.componentTypeList  = new List <ComponentType>();
     this.componentTypeList.Add(ComponentType.MarketManager);
     this.componentTypeList.Add(ComponentType.ReportManager);
     this.activeStops = new Dictionary <Instrument, List <StopBase> >();
     this.portfolios  = new Dictionary <Instrument, Portfolio>();
     this.testers     = new Dictionary <Instrument, LiveTester>();
     this.statisticsPerInstrumentEnabled = false;
 }
示例#15
0
        public override object Clone()
        {
            var p = new AnalyseProject()
            {
                AnalyseEndTime      = AnalyseEndTime,
                AnalyseStartTime    = AnalyseStartTime,
                ProjectStartTime    = ProjectStartTime,
                CurrentDataSource   = CurrentDataSource.Clone() as IDataSource,
                DefaultFilterNumber = DefaultFilterNumber,
                Fine            = Fine,
                Grade           = Grade,
                Memo            = Memo,
                Name            = Name,
                TestStepDelayMS = TestStepDelayMS,
                Status          = Status
            };

            InstrumentList.ForEach(v => p.InstrumentList.Add(v.Clone() as IInstrument));
            ResultList.ForEach(v => p.ResultList.Add(v.Clone() as IInstrument));
            BlockList.ForEach(v => p.BlockList.Add(v.Clone() as IInstrument));
            ConditionList.ForEach(v => p.ConditionList.Add(v.Clone() as ICondition));
            PredicateList.ForEach(v => p.PredicateList.Add(v.Clone() as ICondition));

            return(p);
        }
        void LoadFromDB()
        {
            var connectionStr = ConfigurationManager.ConnectionStrings["MarketDataConnectionString"];

            using (var conn = new SqlConnection(connectionStr.ConnectionString))
            {
                conn.Open();
                var rl = conn.Query <Instrument>("Select * from Table_Instruments", new { }, null, true, 60000).ToList();
                InstrumentList.Clear();
                foreach (var r in rl)
                {
                    r.Ticker    = r.Ticker.Trim();
                    r.Currency  = r.Currency.Trim();
                    r.Industory = r.Industory.Trim();
                    r.Name      = r.Name.Trim();
                    r.Region    = r.Region.Trim();
                    if (r.Memo != null)
                    {
                        r.Memo = r.Memo.Trim();
                    }

                    InstrumentList.Add(r);
                }
            }
            ClearChangedFlag();
        }
示例#17
0
 /// <summary>
 /// Methord Used to get search List.
 /// </summary>
 /// <param name="searchString"></param>
 private void OnSearchChanged(string searchString)
 {
     try
     {
         if (string.IsNullOrWhiteSpace(searchString))
         {
             //Add Elements of InstrumentList to SearchResults When Search String is Empty.
             SearchResults.Clear();
             foreach (var security in InstrumentList)
             {
                 SearchResults.Add(security);
             }
         }
         else
         {
             //Filter InstrumentList according to the Search string and Adds it to SearchResults
             SearchResults.Clear();
             var temp = new ObservableCollection <Security>(InstrumentList.Where(d => d.Symbol.Contains(searchString)));
             foreach (var security in temp)
             {
                 SearchResults.Add(security);
             }
         }
     }
     catch (Exception exception)
     {
         Logger.Error(exception, _oType.FullName, "OnSearchChanged");
     }
 }
示例#18
0
        void RefreshResult()
        {
            ResultList.Clear();
            foreach (var condition in ConditionList)
            {
                var l = condition.GetResult(null, AnalyseEndTime);
                foreach (var r in l)
                {
                    var inst = InstrumentList.FirstOrDefault(v => v.Ticker == r.Ticker);
                    if (inst != null)
                    {
                        if (!ResultList.Any(v => v.Ticker == inst.Ticker))
                        {
                            ResultList.Add(inst);
                        }
                    }
                }
            }

            var rl = new List <IInstrument>();

            foreach (var preicate in PredicateList)
            {
                rl.Clear();
                var l = preicate.GetResult(null, AnalyseEndTime);
                foreach (var r in l)
                {
                    var inst = InstrumentList.FirstOrDefault(v => v.Ticker == r.Ticker);
                    rl.Add(inst);
                }
                ResultList.RemoveAll(v => !rl.Any(r => r.Ticker == v.Ticker));
            }
        }
示例#19
0
		public void Add(InstrumentList instruments, BarType barType, long barSize)
		{
			foreach (Instrument current in instruments)
			{
				this.Add(current, barType, barSize);
			}
		}
示例#20
0
        public override object Clone()
        {
            var p = new BacktestingProject()
            {
                Name              = Name,
                Memo              = Memo,
                IsUnlimited       = IsUnlimited,
                AnalyseGrade      = AnalyseGrade,
                AnalyseStartTime  = AnalyseStartTime,
                CurrentDataSource = CurrentDataSource.Clone() as IDataSource,
                CurrentTradeGate  = CurrentTradeGate,
                Fine              = Fine,
                Grade             = Grade,
                ProjectStartTime  = ProjectStartTime,
                RiskPolicy        = RiskPolicy.Clone() as IRiskControl,
                Status            = Status,
                TargetPortfolio   = TargetPortfolio.Clone() as IPortfolio,
                TestStrategy      = TestStrategy.Clone() as IStrategy,
                TestCurrentTime   = TestCurrentTime,
                TestEndTime       = TestEndTime,
                TestStartTime     = TestStartTime,
                TestStepDelayMS   = TestStepDelayMS,
            };

            ConditionList.ForEach(v => p.ConditionList.Add(v.Clone() as ICondition));
            InstrumentList.ForEach(v => p.InstrumentList.Add(v.Clone() as IInstrument));

            return(p);
        }
 public override void Subscribe(InstrumentList instruments)
 {
     foreach (Instrument current in instruments)
     {
         this.Subscribe(current);
     }
 }
示例#22
0
 public TickFilter(Framework framework, InstrumentList insts)
     : base(framework)
 {
     foreach (var inst in insts)
     {
         _ranges[inst.Id] = TradingCalendar.Instance.GetTimeRange(inst, DateTime.Today);
     }
 }
 void Load(DistributeAnalyse obj)
 {
     TargetObject = obj;
     InstrumentList.Clear();
     TargetObject.InstrumentList.ForEach(v => InstrumentList.Add(v));
     SectorList.Clear();
     TargetObject.SectorList.ForEach(v => SectorList.Add(v));
     CurrentDataSource = TargetObject.CurrentDataSource;
 }
示例#24
0
 public void Init()
 {
     AllInstrumentList.Clear();
     InstrumentList.Clear();
     Instrument.AllInstrumentList.ForEach(r =>
     {
         AllInstrumentList.Add(r);
         InstrumentList.Add(r);
     });
 }
示例#25
0
        public void GenerateResult()
        {
            var sl = InstrumentList.Except(BlockList).ToList();

            if (sl.Count == 0)
            {
                return;
            }
            total = sl.Count;
            Process(sl);
        }
示例#26
0
        //相邻的三元组
        public Dictionary <string, List <Tuple <double, double, double> > > Get3DCurve()
        {
            var r = new Dictionary <string, List <Tuple <double, double, double> > >();

            InstrumentList.ForEach(v =>
            {
                var l = Get3DCurve(v);
                r.Add(v.Name, l);
            });
            return(r);
        }
        public void DeleteTest()
        {
            Instrument     instrument  = new Instrument();
            InstrumentList instruments = new InstrumentList();

            instruments.Load();
            instrument = instruments.FirstOrDefault(i => i.Description == "Update");

            int results = instrument.Delete();

            Assert.IsTrue(results == 1);
        }
示例#28
0
        public int SetInstrumentInfo(string s)
        {
            var l = CommonLib.CommonProc.ConvertStringToObject <List <Instrument> >(s);

            if (l == null || l.Count == 0)
            {
                return(0);
            }
            InstrumentList.Clear();
            l.ForEach(v => InstrumentList.Add(v));
            return(l.Count);
        }
示例#29
0
 // Use this for initialization
 void Start()
 {
     backgroundMusic = GetComponent <AudioSource>();
     instrumentList  = FindObjectOfType <InstrumentList>();
     harps           = Resources.LoadAll <AudioClip>("Audio/Harp");
     flutes          = Resources.LoadAll <AudioClip>("Audio/Flute");
     horns           = Resources.LoadAll <AudioClip>("Audio/Horn");
     player          = GameObject.FindGameObjectWithTag("Player");
     moveScript      = player.GetComponent <BardMovement>();
     progressBar     = FindObjectOfType <ProgressUpdate>();
     canvas          = GameObject.Find("Canvas");
 }
示例#30
0
            public override void OnQueryInstrument(InstrumentList insts)
            {
                Console.WriteLine("- OnQueryInstrument:");

                for (int i = 0; i < insts.Count; i++)
                {
                    Instrument inst = insts[i];
                    PrintInstrumentInfo(inst);

                    //ToDo ...
                }
            }
示例#31
0
 void AnalyseStep()
 {
     InstrumentList.ForEach(v => v.Memo = "");
     ConditionList.ForEach(v => v.ClearResult());
     foreach (var inst in InstrumentList)
     {
         foreach (var condition in ConditionList)
         {
             condition.GenerateResult(inst, AnalyseStartTime, analyseTime, AnalyseGrade);
         }
     }
 }
示例#32
0
        //得到序列里面所有差值的分布
        public Dictionary <string, Tuple <List <Tuple <double, double> >, List <Tuple <double, double> > > > GetDimentionAnalyse(int n = 20)
        {
            var r = new Dictionary <string, Tuple <List <Tuple <double, double> >, List <Tuple <double, double> > > >();

            InstrumentList.ForEach(v =>
            {
                var l  = GetDimentionAnalyse(v, false, n);
                var al = GetDimentionAnalyse(v, true, n);
                r.Add(v.Name, new Tuple <List <Tuple <double, double> >, List <Tuple <double, double> > >(l, al));
            });
            return(r);
        }
示例#33
0
        public OptimizationParameterSet Optimize(Strategy strategy, InstrumentList instruments, OptimizationUniverse universe, int bunch = -1)
        {
            this.event_count = 0L;
            this.watch.Start();
            int num;

            if (bunch == -1)
            {
                num = universe.Count;
            }
            else
            {
                num = bunch;
            }
            int num2 = 0;

            while (num2 + num < universe.Count)
            {
                this.Optimize(strategy, instruments, universe, num2, num);
                num2 += num;
            }
            this.Optimize(strategy, instruments, universe, num2, universe.Count - num2);
            int index = 0;

            for (int i = 1; i < universe.Count; i++)
            {
                if (universe[i].Objective > universe[index].Objective)
                {
                    index = i;
                }
            }
            Console.WriteLine(string.Concat(new object[]
            {
                "Best Objective ",
                universe[index],
                " Objective = ",
                universe[index].Objective
            }));
            Console.WriteLine("Optimization done");
            this.watch.Stop();
            Console.WriteLine(string.Concat(new object[]
            {
                "Processed ",
                this.event_count,
                " events in ",
                this.watch.ElapsedMilliseconds,
                " msec - ",
                (double)this.event_count / (double)this.watch.ElapsedMilliseconds * 1000.0,
                " event/sec"
            }));
            return(universe[index]);
        }
示例#34
0
		public OptimizationParameterSet Optimize(Strategy strategy, InstrumentList instruments, OptimizationUniverse universe, int bunch = -1)
		{
			this.event_count = 0L;
			this.watch.Start();
			int num;
			if (bunch == -1)
			{
				num = universe.Count;
			}
			else
			{
				num = bunch;
			}
			int num2 = 0;
			while (num2 + num < universe.Count)
			{
				this.Optimize(strategy, instruments, universe, num2, num);
				num2 += num;
			}
			this.Optimize(strategy, instruments, universe, num2, universe.Count - num2);
			int index = 0;
			for (int i = 1; i < universe.Count; i++)
			{
				if (universe[i].Objective > universe[index].Objective)
				{
					index = i;
				}
			}
			Console.WriteLine(string.Concat(new object[]
			{
				"Best Objective ",
				universe[index],
				" Objective = ",
				universe[index].Objective
			}));
			Console.WriteLine("Optimization done");
			this.watch.Stop();
			Console.WriteLine(string.Concat(new object[]
			{
				"Processed ",
				this.event_count,
				" events in ",
				this.watch.ElapsedMilliseconds,
				" msec - ",
				(double)this.event_count / (double)this.watch.ElapsedMilliseconds * 1000.0,
				" event/sec"
			}));
			return universe[index];
		}
示例#35
0
 public void Clear()
 {
     foreach (var i in Instruments)
     {
         i.Bid = null;
         i.Ask = null;
         i.Trade = null;
         i.Bar = null;
     }
     var deleted = new InstrumentList();
     foreach (var i in Instruments.Where(i => !i.Loaded))
         deleted.Add(i);
     foreach (var i in deleted)
         Delete(i);
 }
示例#36
0
		public InstrumentManager(Framework framework, InstrumentServer server)
		{
			this.framework = framework;
			this.server = server;
			this.server.Open();
			this.next_id = -1;
			this.instruments = server.Load();
			for (int i = 0; i < this.instruments.Count; i++)
			{
				this.instruments.GetByIndex(i).isPersistent = true;
				int id = this.instruments.GetByIndex(i).Id;
				if (id > this.next_id)
				{
					this.next_id = id;
				}
			}
			this.next_id++;
		}
示例#37
0
 public Strategy(Framework framework, string name)
 {
     this.framework = framework;
     this.Name = name;
     this.strategiesByInstrument = new IdArray<LinkedList<Strategy>>(1000);
     this.strategyByOrderId = new IdArray<Strategy>(1000);
     this.strategies = new LinkedList<Strategy>();
     this.status = StrategyStatus.Stopped;
     this.instruments = new InstrumentList();
     this.instrumentCountTable = new IdArray<int>(1000);
     if (framework != null)
     {
         this.portfolio = new Portfolio(framework, this.Name);
         framework.PortfolioManager.Add(this.portfolio);
     }
     this.bars = new BarSeries("", "");
     this.equity = new TimeSeries();
     this.bids = new TickSeries("");
     this.asks = new TickSeries("");
     this.stops = new List<Stop>();
     this.stopsByInstrument = new IdArray<List<Stop>>(1000);
 }
示例#38
0
 internal void RegisterStrategy(Strategy strategy, InstrumentList instruments, int orderRouteId)
 {
     strategy.portfolio.Parent = this.portfolio;
     foreach (Instrument current in instruments)
     {
         LinkedList<Strategy> linkedList;
         if (this.strategiesByInstrument[current.Id] == null)
         {
             linkedList = new LinkedList<Strategy>();
             this.strategiesByInstrument[current.Id] = linkedList;
         }
         else
         {
             linkedList = this.strategiesByInstrument[current.Id];
         }
         linkedList.Add(strategy);
         IdArray<int> idArray;
         int num;
         (idArray = this.instrumentCountTable)[num = current.id] = idArray[num] + 1;
     }
     Dictionary<IDataProvider, InstrumentList> dictionary = new Dictionary<IDataProvider, InstrumentList>();
     foreach (Instrument current2 in instruments)
     {
         InstrumentList instrumentList = null;
         IDataProvider dataProvider = this.GetDataProvider(strategy, current2);
         IExecutionProvider executionProvider = strategy.GetExecutionProvider(current2);
         if (dataProvider.Status == ProviderStatus.Disconnected)
         {
             dataProvider.Connect();
         }
         if (executionProvider.Status == ProviderStatus.Disconnected)
         {
             executionProvider.Connect();
         }
         if (!dictionary.TryGetValue(dataProvider, out instrumentList))
         {
             instrumentList = new InstrumentList();
             dictionary[dataProvider] = instrumentList;
         }
         instrumentList.Add(current2);
     }
     foreach (KeyValuePair<IDataProvider, InstrumentList> current3 in dictionary)
     {
         this.framework.strategyManager.RegisterMarketDataRequest(current3.Key, current3.Value);
     }
     this.strategyByOrderId[orderRouteId] = strategy;
     if (this.parent != null)
     {
         this.parent.RegisterStrategy(this, instruments, orderRouteId);
     }
 }
示例#39
0
        public override void Subscribe(InstrumentList instruments)
        {
            foreach (var instrument in instruments)
                Subscribe(instrument, this.running ? this.framework.Clock.DateTime : DateTime1, DateTime2);

            if (!this.running && RunOnSubscribe)
                Run();
        }
示例#40
0
 public abstract void SubscribeL1(InstrumentList instruments);
示例#41
0
 internal void UnregisterStrategy(Strategy strategy, InstrumentList instruments, int orderRouteId)
 {
     strategy.portfolio.Parent = this.portfolio;
     foreach (Instrument current in instruments)
     {
         LinkedList<Strategy> linkedList = this.strategiesByInstrument[current.Id];
         if (linkedList != null)
         {
             linkedList.Remove(strategy);
         }
         linkedList.Add(strategy);
         IdArray<int> idArray;
         int num;
         (idArray = this.instrumentCountTable)[num = current.id] = idArray[num] - 1;
         if (this.instrumentCountTable[current.id] == 0)
         {
             this.Instruments.Remove(current);
         }
     }
     Dictionary<IDataProvider, InstrumentList> dictionary = new Dictionary<IDataProvider, InstrumentList>();
     foreach (Instrument current2 in instruments)
     {
         InstrumentList instrumentList = null;
         IDataProvider key = this.GetDataProvider(strategy, current2);
         if (!dictionary.TryGetValue(key, out instrumentList))
         {
             instrumentList = new InstrumentList();
             dictionary[key] = instrumentList;
         }
         instrumentList.Add(current2);
     }
     foreach (KeyValuePair<IDataProvider, InstrumentList> current3 in dictionary)
     {
         this.framework.strategyManager.UnregisterMarketDataRequest(current3.Key, current3.Value);
     }
     this.strategyByOrderId[orderRouteId] = null;
     if (this.parent != null)
     {
         this.parent.UnregisterStrategy(this, instruments, orderRouteId);
     }
 }
示例#42
0
        public void RegisterMarketDataRequest(IDataProvider dataProvider, InstrumentList instrumentList)
        {
            InstrumentList alreadyRegistered = null;
            if (!this.subscriptions.TryGetValue(dataProvider, out alreadyRegistered))
            {
                alreadyRegistered = new InstrumentList();
                this.subscriptions[dataProvider] = alreadyRegistered;
            }

            foreach (var current in instrumentList)
                if (!alreadyRegistered.Contains(current.Id))
                    alreadyRegistered.Add(current);

            if (Status == StrategyStatus.Running)
                this.framework.SubscriptionManager?.Subscribe(dataProvider, instrumentList);
        }
示例#43
0
 public void RemoveInstrument(Instrument instrument)
 {
     this.instruments.Remove(instrument);
     InstrumentList instrumentList = new InstrumentList();
     instrumentList.Add(instrument);
     this.framework.strategyManager.UnregisterMarketDataRequest(this.GetDataProvider(this, instrument), instrumentList);
     if (this.parent != null)
     {
         this.parent.UnregisterStrategy(this, instrumentList, (int)this.id);
     }
 }
示例#44
0
 public void AddInstruments(InstrumentList instruments)
 {
     foreach (Instrument current in instruments)
     {
         this.AddInstrument(current);
     }
 }
 public override void Unsubscribe(InstrumentList instruments)
 {
     foreach (Instrument current in instruments)
     {
         SellSideInstrumentStrategy sellSideInstrumentStrategy = this.strategyBySynthInstrument[current.Id];
         sellSideInstrumentStrategy.OnUnsubscribe(current);
     }
 }
示例#46
0
		public override void Subscribe(InstrumentList instruments)
		{
			if (!this.isRunning)
			{
				foreach (Instrument current in instruments)
				{
					this.Subscribe_(current, this.dateTime1, this.dateTime2);
				}
				this.Run();
				return;
			}
			foreach (Instrument current2 in instruments)
			{
				this.Subscribe_(current2, this.framework.Clock.DateTime, this.dateTime2);
			}
		}
示例#47
0
 public virtual void Unsubscribe(InstrumentList instruments)
 {
     OnUnsubscribe(instruments);
 }
示例#48
0
 public override void Unsubscribe(InstrumentList instruments)
 {
     foreach (var current in instruments)
         Unsubscribe(current);
 }
示例#49
0
 protected virtual void OnSubscribe(InstrumentList instruments)
 {
     // noop
 }
示例#50
0
 public OnUnsubscribe(InstrumentList instruments)
 {
     Instruments = instruments;
 }
示例#51
0
 public void Unsubscribe(IDataProvider provider, InstrumentList instruments)
 {
     InstrumentList instrumentList = new InstrumentList();
     for (int i = 0; i < instruments.Count; i++)
     {
         Instrument byIndex = instruments.GetByIndex(i);
         Dictionary<Instrument, int> dictionary;
         Instrument key;
         (dictionary = this.subscriptions[(int)provider.Id])[key = byIndex] = dictionary[key] - 1;
         if (this.subscriptions[(int)provider.Id][byIndex] == 0)
         {
             instrumentList.Add(byIndex);
         }
     }
     provider.Unsubscribe(instrumentList);
 }
示例#52
0
 private void RegisterInstrument(Instrument instrument)
 {
     InstrumentList instrumentList = new InstrumentList();
     instrumentList.Add(instrument);
     IDataProvider dataProvider = this.GetDataProvider(this, instrument);
     IExecutionProvider executionProvider = this.GetExecutionProvider(instrument);
     if (dataProvider.Status == ProviderStatus.Disconnected)
     {
         dataProvider.Connect();
     }
     if (executionProvider.Status == ProviderStatus.Disconnected)
     {
         executionProvider.Connect();
     }
     this.framework.strategyManager.RegisterMarketDataRequest(dataProvider, instrumentList);
     if (this.parent != null)
     {
         this.parent.RegisterStrategy(this, instrumentList, (int)this.id);
     }
 }
示例#53
0
 public void Add(InstrumentList instruments, BarType barType, long barSize, BarInput barInput = BarInput.Trade,
     ClockType type = ClockType.Local, int providerId = -1)
 {
     foreach (var i in instruments)
         Add(i, barType, barSize, barInput, type, providerId);
 }
示例#54
0
		public void Clear()
		{
			foreach (Instrument current in this.instruments)
			{
				current.bid = null;
				current.ask = null;
				current.trade = null;
			}
			InstrumentList instrumentList = new InstrumentList();
			foreach (Instrument current2 in this.instruments)
			{
				if (!current2.isPersistent)
				{
					instrumentList.Add(current2);
				}
			}
			foreach (Instrument current3 in instrumentList)
			{
				this.Delete(current3);
			}
		}
示例#55
0
 public void RegisterMarketDataRequest(IDataProvider dataProvider, InstrumentList instrumentList)
 {
     InstrumentList instrumentList2 = new InstrumentList();
     InstrumentList instrumentList3 = null;
     if (!this.requests.TryGetValue(dataProvider, out instrumentList3))
     {
         instrumentList3 = new InstrumentList();
         this.requests[dataProvider] = instrumentList3;
     }
     foreach (Instrument current in instrumentList)
     {
         if (!instrumentList3.Contains(current.id))
         {
             instrumentList3.Add(current);
             instrumentList2.Add(current);
         }
     }
     if (this.status == StrategyStatus.Running && instrumentList2.Count > 0 && this.framework.SubscriptionManager != null)
     {
         this.framework.SubscriptionManager.Subscribe(dataProvider, instrumentList2);
     }
 }
示例#56
0
 public virtual void Unsubscribe(InstrumentList instruments)
 {
     Console.WriteLine($"{nameof(SellSideStrategy)}::{nameof(Unsubscribe)} {instruments}");
     OnUnsubscribe(instruments);
 }
示例#57
0
 protected virtual void OnUnsubscribe(InstrumentList instruments)
 {
 }
示例#58
0
 public void Add(InstrumentList instruments)
 {
     foreach (Instrument current in instruments)
     {
         this.Add(current, null);
     }
 }
示例#59
0
        public void StartStrategy(Strategy strategy, StrategyMode mode)
        {
            lock (this)
            {
                this.subscriptions.Clear();
                Strategy = strategy;
                Mode = mode;
                if (this.framework.Mode == FrameworkMode.Simulation)
                {
                    this.framework.Clock.DateTime = this.framework.ProviderManager.DataSimulator.DateTime1;
                    this.framework.ExchangeClock.DateTime = DateTime.MinValue;
                }
                if (this.framework.EventManager.Status != EventManagerStatus.Running)
                    this.framework.EventManager.Start();

                SetStatusType(StrategyStatusType.Started);
                if (Persistence == StrategyPersistence.Full || Persistence == StrategyPersistence.Load)
                {
                    this.framework.PortfolioManager.Load(strategy.Name);
                    this.framework.OrderManager.Load(strategy.Name, -1);
                    this.framework.OrderServer.SeriesName = strategy.Name;
                    this.framework.OrderManager.IsPersistent = true;
                }
                else
                {
                    this.framework.OrderManager.IsPersistent = false;
                }

                strategy.Init();

                if ((Persistence == StrategyPersistence.Full || Persistence == StrategyPersistence.Save) && !strategy.Portfolio.IsLoaded)
                    this.framework.PortfolioManager.Save(strategy.Portfolio);
              
                strategy.EmitStrategyStart();

                if (!this.framework.IsExternalDataQueue)
                {
                    var dictionary = new Dictionary<IDataProvider, InstrumentList>();
                    while (this.subscriptions.Count != 0)
                    {
                        var dictionary2 = new Dictionary<IDataProvider, InstrumentList>(this.subscriptions);
                        this.subscriptions.Clear();
                        foreach (var current in dictionary2)
                        {
                            InstrumentList instrumentList = null;
                            if (!dictionary.TryGetValue(current.Key, out instrumentList))
                            {
                                instrumentList = new InstrumentList();
                                dictionary[current.Key] = instrumentList;
                            }
                            InstrumentList instrumentList2 = new InstrumentList();
                            foreach (Instrument current2 in current.Value)
                            {
                                if (!instrumentList.Contains(current2))
                                {
                                    instrumentList.Add(current2);
                                    instrumentList2.Add(current2);
                                }
                            }
                            if (current.Key is SellSideStrategy)
                            {
                                this.framework.SubscriptionManager?.Subscribe(current.Key, instrumentList2);
                            }
                        }
                    }
                    SetParametersGroup();
                    Status = StrategyStatus.Running;
                    this.subscriptions = dictionary;
                    if (this.subscriptions.Count == 0 && mode == StrategyMode.Backtest)
                    {
                        Console.WriteLine($"{DateTime.Now } StrategyManager::StartStrategy {strategy.Name} has no data requests in backtest mode, stopping...");
                        StopStrategy();
                    }
                    else
                    {
                        foreach (var current3 in this.subscriptions)
                        {
                            if (!(current3.Key is SellSideStrategy))
                                this.framework.SubscriptionManager?.Subscribe(current3.Key, current3.Value);
                        }
                        if (mode != StrategyMode.Backtest)
                            strategy.FundamentalProvider?.Connect();
                    }
                }
                else
                {
                    SetParametersGroup();
                    Status = StrategyStatus.Running;
                }
            }
        }
示例#60
0
        internal void UnregisterMarketDataRequest(IDataProvider dataProvider, InstrumentList instruments)
        {
            if (Status == StrategyStatus.Running && instruments.Count > 0)
                this.framework.SubscriptionManager?.Unsubscribe(dataProvider, instruments);

            var list = this.subscriptions[dataProvider];
            if (list != null)
            {
                foreach (var i in instruments)
                    if (!this.framework.SubscriptionManager.IsSubscribed(dataProvider, i))
                        list.Remove(i);
            }
        }