#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Community.Community File: StrategyClient.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Community { using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Threading; using Ecng.Collections; using Ecng.Common; /// /// The client for access to . /// [CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)] public class StrategyClient : BaseCommunityClient { private Timer _refreshTimer; private DateTime _lastCheckTime; private readonly CachedSynchronizedDictionary _strategies = new CachedSynchronizedDictionary(); private readonly CachedSynchronizedDictionary _subscriptions = new CachedSynchronizedDictionary(); private readonly CachedSynchronizedDictionary _backtests = new CachedSynchronizedDictionary(); private readonly CachedSynchronizedDictionary _backtestResults = new CachedSynchronizedDictionary(); private readonly CachedSynchronizedDictionary _startedBacktests = new CachedSynchronizedDictionary(); /// /// Initializes a new instance of the . /// public StrategyClient() : this(new Uri("http://stocksharp.com/services/strategyservice.svc")) { } /// /// Initializes a new instance of the . /// /// Server address. public StrategyClient(Uri address) : base(address, "strategy") { } /// /// All strategies. /// public IEnumerable Strategies { get { EnsureInit(); return _strategies.CachedValues; } } /// /// Strategy subscriptions signed by . /// public IEnumerable Subscriptions { get { EnsureInit(); return _subscriptions.CachedValues; } } /// /// All strategy backtests. /// public IEnumerable StrategyBacktests { get { EnsureInit(); return _backtests.CachedValues; } } /// /// A new strategy was created in the store. /// public event Action StrategyCreated; /// /// Existing strategy was updated in the store. /// public event Action StrategyUpdated; /// /// Existing strategy was deleted from the store. /// public event Action StrategyDeleted; /// /// Strategy was subscribed. /// public event Action StrategySubscribed; /// /// Strategy was unsubscribed. /// public event Action StrategyUnSubscribed; /// /// Backtesting process has changed. /// public event Action BacktestProgressChanged; /// /// Backtesting process has stopped. /// public event Action BacktestStopped; private void EnsureInit() { if (_refreshTimer != null) return; Refresh(); var subscriptions = Invoke(f => f.GetSubscriptions(SessionId, DateTime.MinValue)); foreach (var subscription in subscriptions) { _subscriptions.Add(subscription.Id, subscription); } var backtests = Invoke(f => f.GetBacktests(SessionId, DateTime.Today - TimeSpan.FromDays(5), DateTime.UtcNow)); foreach (var backtest in backtests) { _backtests.Add(backtest.Id, backtest); } _refreshTimer = ThreadingHelper .Timer(Refresh) .Interval(TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); } private void Refresh() { var ids = Invoke(f => f.GetStrategies(_lastCheckTime)).ToArray(); foreach (var tuple in ids.Where(t => t.Item2 < 0)) { var strategy = _strategies.TryGetValue(tuple.Item1); if (strategy != null) StrategyDeleted?.Invoke(strategy); } var newIds = new List(); var updatedIds = new List(); foreach (var tuple in ids.Where(t => t.Item2 >= 0)) { var strategy = _strategies.TryGetValue(tuple.Item1); if (strategy != null) updatedIds.Add(tuple.Item1); else newIds.Add(tuple.Item1); } var newStrategies = Invoke(f => f.GetDescription(newIds.ToArray())); foreach (var newStrategy in newStrategies) { _strategies.Add(newStrategy.Id, newStrategy); StrategyCreated?.Invoke(newStrategy); } var updatedStrategies = Invoke(f => f.GetDescription(updatedIds.ToArray())); foreach (var updatedStrategy in updatedStrategies) { var strategy = _strategies[updatedStrategy.Id]; CopyTo(updatedStrategy, strategy); StrategyUpdated?.Invoke(strategy); } _lastCheckTime = DateTime.Now; foreach (var backtest in _backtests.CachedValues) { if (_backtestResults.ContainsKey(backtest)) continue; var resultId = Invoke(f => f.GetBacktestResult(SessionId, backtest.Id)); if (resultId == null) continue; _backtestResults.Add(backtest, resultId.Value); BacktestStopped?.Invoke(backtest); _startedBacktests.Remove(backtest); } foreach (var backtest in _startedBacktests.CachedKeys) { var count = Invoke(f => f.GetCompletedIterationCount(SessionId, backtest.Id)); var prevCount = _startedBacktests[backtest]; if (count == prevCount) continue; BacktestProgressChanged?.Invoke(backtest, count); if (count == backtest.Iterations.Length) _startedBacktests.Remove(backtest); else _startedBacktests[backtest] = count; } } private static void CopyTo(StrategyData source, StrategyData destination) { destination.Name = source.Name; //destination.EnName = source.EnName; destination.Description = source.Description; //destination.EnDescription = source.EnDescription; destination.Price = source.Price; destination.Revision = source.Revision; destination.DescriptionId = source.DescriptionId; destination.Content = source.Content; destination.ContentType = source.ContentType; } /// /// To add the strategy to the store. /// /// The strategy data. public void CreateStrategy(StrategyData strategy) { var id = Invoke(f => f.CreateStrategy(SessionId, strategy)); if (id < 0) ValidateError((byte)-id, strategy.Id, strategy.Price); else strategy.Id = id; _strategies.Add(id, strategy); StrategyCreated?.Invoke(strategy); } /// /// To update the strategy in the store. /// /// The strategy data. public void UpdateStrategy(StrategyData strategy) { ValidateError(Invoke(f => f.UpdateStrategy(SessionId, strategy)), strategy.Id); StrategyUpdated?.Invoke(strategy); } /// /// To remove the strategy from the store. /// /// The strategy data. public void DeleteStrategy(StrategyData strategy) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); ValidateError(Invoke(f => f.DeleteStrategy(SessionId, strategy.Id)), strategy.Id); _strategies.Remove(strategy.Id); StrategyDeleted?.Invoke(strategy); } ///// ///// To get the source or executable codes. ///// ///// The strategy data. //public void Download(StrategyData strategy) //{ // if (strategy == null) // throw new ArgumentNullException(nameof(strategy)); // var content = Invoke(f => f.GetContent(SessionId, strategy.Id)); // strategy.Revision = content.Revision; // strategy.Content = content.Content; // strategy.ContentName = content.ContentName; //} /// /// To subscribe for the strategy. /// /// Is auto renewable subscription. /// The strategy data. /// The strategy subscription. public StrategySubscription Subscribe(StrategyData strategy, bool isAutoRenew) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); var subscription = Invoke(f => f.Subscribe(SessionId, strategy.Id, isAutoRenew)); if (subscription.Id < 0) ValidateError((byte)-subscription.Id, strategy.Id); else { lock (_subscriptions.SyncRoot) { var prevSubscr = _subscriptions.TryGetValue(subscription.Id); if (prevSubscr == null) _subscriptions.Add(subscription.Id, subscription); else subscription = prevSubscr; } StrategySubscribed?.Invoke(subscription); } return subscription; } /// /// To unsubscribe from the strategy. /// /// The strategy subscription. public void UnSubscribe(StrategySubscription subscription) { if (subscription == null) throw new ArgumentNullException(nameof(subscription)); ValidateError(Invoke(f => f.UnSubscribe(SessionId, subscription.Id))); StrategyUnSubscribed?.Invoke(subscription); _subscriptions.Remove(subscription.Id); } /// /// To get an approximate of money to spend for the specified backtesting configuration. /// /// Backtesting session. /// An approximate of money. public decimal GetApproximateAmount(StrategyBacktest backtest) { return Invoke(f => f.GetApproximateAmount(SessionId, backtest)); } /// /// To start backtesing. /// /// Backtesting session. public void StartBacktest(StrategyBacktest backtest) { backtest.Id = Invoke(f => f.StartBacktest(SessionId, backtest)); _backtests.Add(backtest.Id, backtest); _startedBacktests.Add(backtest, 0); } /// /// To stop the backtesing. /// /// Backtesting session. public void StopBacktest(StrategyBacktest backtest) { ValidateError(Invoke(f => f.StopBacktest(SessionId, backtest.Id))); } private static void ValidateError(byte errorCode, params object[] args) { ((ErrorCodes)errorCode).ThrowIfError(args); } /// /// Release resources. /// protected override void DisposeManaged() { _refreshTimer?.Dispose(); base.DisposeManaged(); } } }