Ejemplo n.º 1
0
        static void Run()
        {
            var            exchanges = _container.ResolveAll <IExchange>().ToArray();
            ITradeStrategy strategy  = _container.Resolve <ITradeStrategy>();

            Task[] exchangeUpdateTasks = new Task[exchanges.Count()];


            for (int i = 0; i < exchanges.Count(); i++)
            {
                var exchange = exchanges[i];

                var execution = Task.Factory.StartNew(() =>
                {
                    while (running)
                    {
                        exchange.UpdateQuotes();

                        lock (strategyLock)
                        {
                            strategy.Execute();
                        }
                    }
                });
                exchangeUpdateTasks[i] = execution;
            }

            //Use array to minimize main thread startup
            Task.WaitAll(exchangeUpdateTasks);
        }
 public TradingHeartbeatSpoofingProcess(
     IPulsatingHeartbeat heartbeat,
     ILogger logger,
     ITradeStrategy <Order> orderStrategy)
     : base(logger, orderStrategy)
 {
     this._heartbeat = heartbeat ?? throw new ArgumentNullException(nameof(heartbeat));
 }
Ejemplo n.º 3
0
 public TradingLayeringProcess(
     IReadOnlyCollection <DataGenerationPlan> plan,
     ITradeStrategy <Order> orderStrategy,
     ILogger logger)
     : base(logger, orderStrategy)
 {
     this._intraDayHistoryStack = new EquityIntraDayHistoryStack(TimeSpan.FromHours(1));
     this._plan = plan ?? new DataGenerationPlan[0];
 }
Ejemplo n.º 4
0
        public bool TryAddTradeStrategy(string strategyName, ITradeStrategy tradeStrategy)
        {
            if (tradeStrategies.TryAdd(strategyName, tradeStrategy))
            {
                OnServerNotification();
                return(true);
            }

            return(false);
        }
 public TradingCancelledOrderTradeProcess(
     ITradeStrategy <Order> orderStrategy,
     IReadOnlyCollection <string> cancelTargetSedols,
     DateTime triggerCount,
     ILogger logger)
     : base(logger, orderStrategy)
 {
     this._cancelTargetSedols = cancelTargetSedols ?? new string[0];
     this._triggerCount       = triggerCount;
 }
Ejemplo n.º 6
0
        public bool TryRemoveTradeStrategy(string strategyName, out ITradeStrategy tradeStrategy)
        {
            if (tradeStrategies.TryRemove(strategyName, out tradeStrategy))
            {
                OnServerNotification();
                return(true);
            }

            return(false);
        }
 public TradingHighVolumeTradeProcess(
     IReadOnlyCollection <string> cancelTargetSedols,
     ITradeStrategy <Order> orderStrategy,
     ILogger logger)
     : base(logger, orderStrategy)
 {
     this._highVolumeTargetSedols = cancelTargetSedols?.Where(cts => !string.IsNullOrWhiteSpace(cts))?.ToList()
                                    ?? new List <string>();
     this._intraDayHistoryStack = new EquityIntraDayHistoryStack(TimeSpan.FromHours(2));
 }
Ejemplo n.º 8
0
        public static bool IsEnded(this ITradeStrategy strategy)
        {
            if (strategy == null)
            {
                return(true);
            }

            var status = strategy.GetStatus();

            return(status == TradeStrategyStatus.Cancelled || status == TradeStrategyStatus.Failed || status == TradeStrategyStatus.Completed);
        }
Ejemplo n.º 9
0
        public void Setup()
        {
            this._unsubscriber  = A.Fake <IDisposable>();
            this._stockStream   = A.Fake <IStockExchangeStream>();
            this._tradeStream   = A.Fake <IOrderStream <Order> >();
            this._tradeStrategy = A.Fake <ITradeStrategy <Order> >();
            this._logger        = A.Fake <ILogger>();

            A.CallTo(() => this._stockStream.Subscribe(A <IObserver <EquityIntraDayTimeBarCollection> > .Ignored))
            .Returns(this._unsubscriber);
        }
Ejemplo n.º 10
0
 public TradingMarkingTheCloseProcess(
     IReadOnlyCollection <string> markingTheCloseTargetSedols,
     ITradeStrategy <Order> orderStrategy,
     ExchangeDto marketDto,
     ILogger logger)
     : base(logger, orderStrategy)
 {
     this._markingTheCloseTargetSedols =
         markingTheCloseTargetSedols?.Where(cts => !string.IsNullOrWhiteSpace(cts))?.ToList()
         ?? new List <string>();
     this._intraDayHistoryStack = new EquityIntraDayHistoryStack(TimeSpan.FromMinutes(29));
     this._marketDto            = marketDto ?? throw new ArgumentNullException(nameof(marketDto));
 }
Ejemplo n.º 11
0
        public void Unsubscribe(Strategy strategy, ITradeStrategy tradeStrategy)
        {
            if (strategy == null)
            {
                throw new ArgumentNullException(nameof(strategy));
            }

            var exchangeSymbolsList = (from s in strategy.StrategySubscriptions
                                       group s by s.Exchange into es
                                       select new { Exchange = es.Key, StrategySubscriptions = es.ToList() }).ToList();

            foreach (var exchangeSymbols in exchangeSymbolsList)
            {
                var exchangeSubscriptionsCache = ExchangeSubscriptionsCacheFactory.GetExchangeSubscriptionsCache(exchangeSymbols.Exchange);
                exchangeSubscriptionsCache.Unsubscribe(strategy.Name, exchangeSymbols.StrategySubscriptions, tradeStrategy);
            }
        }
 public TradingWashTradeProcess(ITradeStrategy <Order> orderStrategy, DataGenerationPlan plan, ILogger logger)
     : base(logger, orderStrategy)
 {
     this._plan = plan;
     this._thirdGroupActivation = this._plan.EquityInstructions.TerminationInUtc.AddHours(4);
 }
Ejemplo n.º 13
0
 public void Process(ITradeStrategy strategy)
 {
     _executing.Add(new ExecutingTrade(strategy));
     strategy.Start();
 }
 protected BaseTradingProcess(ILogger logger, ITradeStrategy <Order> orderStrategy)
 {
     this.Logger        = logger ?? throw new ArgumentNullException(nameof(logger));
     this.OrderStrategy = orderStrategy ?? throw new ArgumentNullException(nameof(orderStrategy));
 }
Ejemplo n.º 15
0
        public async Task Subscribe(string strategyName, List <StrategySubscription> strategySubscriptions, ITradeStrategy tradeStrategy)
        {
            if (strategySubscriptions == null)
            {
                throw new ArgumentNullException(nameof(strategySubscriptions));
            }

            if (tradeStrategy == null)
            {
                throw new ArgumentNullException(nameof(tradeStrategy));
            }

            await tradeStrategy.AddExchangeService(strategySubscriptions, exchange, exchangeService).ConfigureAwait(false);

            var exchangeApi = exchangeService.GetExchangeApi(exchange);

            foreach (var strategySubscription in strategySubscriptions)
            {
                if (strategySubscription.Subscribes.HasFlag(Subscribes.Trades) ||
                    strategySubscription.Subscribes.HasFlag(Subscribes.OrderBook) ||
                    strategySubscription.Subscribes.HasFlag(Subscribes.Candlesticks))
                {
                    if (!Caches.TryGetValue(strategySubscription.Symbol, out ISubscriptionCache symbolCache))
                    {
                        symbolCache = new SymbolSubscriptionCache(strategySubscription.Symbol, strategySubscription.Limit, strategySubscription.CandlestickInterval, exchangeApi);
                        Caches.TryAdd(strategySubscription.Symbol, symbolCache);
                    }

                    symbolCache.Subscribe(strategyName, strategySubscription, tradeStrategy);
                }

                if (strategySubscription.Subscribes.HasFlag(Subscribes.AccountInfo))
                {
                    var user = new User
                    {
                        ApiKey        = strategySubscription.ApiKey,
                        ApiSecret     = strategySubscription.SecretKey,
                        ApiPassPhrase = strategySubscription.ApiPassPhrase,
                        Exchange      = strategySubscription.Exchange
                    };

                    var accountInfo = await exchangeService.GetAccountInfoAsync(exchange, user, new CancellationToken()).ConfigureAwait(false);

                    tradeStrategy.SubscribeAccountInfo(new AccountInfoEventArgs {
                        AccountInfo = accountInfo
                    });

                    if (!Caches.TryGetValue(strategySubscription.ApiKey, out ISubscriptionCache accountInfoCache))
                    {
                        accountInfoCache = new AccountInfoSubscriptionCache(exchangeApi);
                        Caches.TryAdd(strategySubscription.ApiKey, accountInfoCache);
                    }

                    accountInfoCache.Subscribe(strategyName, strategySubscription, tradeStrategy);
                }
            }
        }
Ejemplo n.º 16
0
        public void Unsubscribe(string strategyName, List <StrategySubscription> strategySubscriptions, ITradeStrategy tradeStrategy)
        {
            if (strategySubscriptions == null)
            {
                throw new ArgumentNullException(nameof(strategySubscriptions));
            }

            foreach (var strategySubscription in strategySubscriptions)
            {
                if (strategySubscription.Subscribes.HasFlag(Subscribes.Trades) ||
                    strategySubscription.Subscribes.HasFlag(Subscribes.OrderBook) ||
                    strategySubscription.Subscribes.HasFlag(Subscribes.Candlesticks))
                {
                    Unsubscribe(strategyName, strategySubscription, strategySubscription.Symbol, tradeStrategy);
                }

                if (strategySubscription.Subscribes.HasFlag(Subscribes.AccountInfo))
                {
                    Unsubscribe(strategyName, strategySubscription, strategySubscription.ApiKey, tradeStrategy);
                }
            }
        }
Ejemplo n.º 17
0
        internal async Task <Strategy> RunStrategyAsync(Strategy strategy, string localPath)
        {
            ITradeStrategy tradeStrategy = null;

            try
            {
                Notify(NotificationLevel.Information, NotificationEventId.RunStrategyAsync, strategy, $"Loading {strategy.Name}");

                var dependencies = GetAssemblies(localPath);

                var     assemblyLoader = new AssemblyLoader(localPath, dependencies);
                var     assembly       = assemblyLoader.LoadFromMemoryStream(Path.Combine(localPath, strategy.TargetAssembly));
                var     type           = assembly.GetType(strategy.TargetType);
                dynamic obj            = Activator.CreateInstance(type);

                tradeStrategy = (ITradeStrategy)obj;

                tradeStrategy.StrategyNotificationEvent       += StrategyNotificationEvent;
                tradeStrategy.StrategyAccountInfoEvent        += StrategyAccountInfoEvent;
                tradeStrategy.StrategyOrderBookEvent          += StrategyOrderBookEvent;
                tradeStrategy.StrategyTradeEvent              += StrategyTradeEvent;
                tradeStrategy.StrategyStatisticsEvent         += StrategyStatisticsEvent;
                tradeStrategy.StrategyCandlesticksEvent       += StrategyCandlesticksEvent;
                tradeStrategy.StrategyParameterUpdateEvent    += StrategyParameterUpdateEvent;
                tradeStrategy.StrategyCustomNotificationEvent += StrategyCustomNotificationEvent;

                tradeStrategy.SetStrategy(strategy);

                strategy.Status = StrategyStatus.Running;

                if (tradeStrategyCacheManager.TryAddTradeStrategy(strategy.Name, tradeStrategy))
                {
                    Notify(NotificationLevel.Information, NotificationEventId.RunStrategyAsync, strategy, $"Subscribing {strategy.Name}");

                    await subscriptionsCacheManager.Subscribe(strategy, tradeStrategy).ConfigureAwait(false);

                    Notify(NotificationLevel.Information, NotificationEventId.RunStrategyAsync, strategy, $"Running {strategy.Name}");

                    var result = await tradeStrategy.RunAsync(cancellationToken).ConfigureAwait(false);

                    if (!tradeStrategyCacheManager.TryRemoveTradeStrategy(strategy.Name, out ITradeStrategy ts))
                    {
                        Notify(NotificationLevel.Error, NotificationEventId.RunStrategyAsync, strategy, $"Failed to remove {strategy.Name} from the cache manager.");
                    }
                }
                else
                {
                    Notify(NotificationLevel.Error, NotificationEventId.RunStrategyAsync, strategy, $"Failed to add {strategy.Name} to the cache manager.");
                }
            }
            finally
            {
                if (tradeStrategy != null)
                {
                    subscriptionsCacheManager.Unsubscribe(strategy, tradeStrategy);

                    tradeStrategy.StrategyNotificationEvent       -= StrategyNotificationEvent;
                    tradeStrategy.StrategyAccountInfoEvent        -= StrategyAccountInfoEvent;
                    tradeStrategy.StrategyOrderBookEvent          -= StrategyOrderBookEvent;
                    tradeStrategy.StrategyTradeEvent              -= StrategyTradeEvent;
                    tradeStrategy.StrategyParameterUpdateEvent    -= StrategyParameterUpdateEvent;
                    tradeStrategy.StrategyCustomNotificationEvent -= StrategyCustomNotificationEvent;
                }

                // TODO: Unload target assembly and it's dependencies from memory and delete them.
            }

            return(strategy);
        }
Ejemplo n.º 18
0
 public async Task Subscribe(string strategyName, List <StrategySubscription> strategySubscription, ITradeStrategy tradeStrategy)
 {
     await Task.Run(() =>
     {
         foreach (var subscription in strategySubscription)
         {
             Caches.TryAdd(subscription.Symbol, new TestSubscriptionCache());
         }
     });
 }
Ejemplo n.º 19
0
 public RequestTradeMessage(ITradeStrategy strategy) : base(strategy.Id)
 {
     Strategy = strategy;
 }
Ejemplo n.º 20
0
 public ExecutingTrade(ITradeStrategy strategy)
 {
     Strategy = strategy;
 }
Ejemplo n.º 21
0
        public void Unsubscribe(string strategyName, StrategySubscription strategySubscription, ITradeStrategy tradeStrategy)
        {
            if (strategySubscription == null)
            {
                throw new ArgumentNullException(nameof(strategySubscription));
            }

            if (tradeStrategy == null)
            {
                throw new ArgumentNullException(nameof(tradeStrategy));
            }

            if (strategySubscription.Subscribes.HasFlag(Subscribes.AccountInfo))
            {
                subscribeAccountInfo.Unsubscribe(strategyName, tradeStrategy.SubscribeAccountInfoException);
            }
        }
Ejemplo n.º 22
0
        public void Subscribe(string strategyName, StrategySubscription strategySubscription, ITradeStrategy tradeStrategy)
        {
            if (strategySubscription == null)
            {
                throw new ArgumentNullException(nameof(strategySubscription));
            }

            if (tradeStrategy == null)
            {
                throw new ArgumentNullException(nameof(tradeStrategy));
            }

            if (strategySubscription.Subscribes.HasFlag(Subscribes.AccountInfo))
            {
                var accountInfo = new StrategyNotification <AccountInfoEventArgs>
                {
                    Update    = tradeStrategy.SubscribeAccountInfo,
                    Exception = tradeStrategy.SubscribeAccountInfoException
                };

                subscribeAccountInfo.User.ApiKey    = strategySubscription.ApiKey;
                subscribeAccountInfo.User.ApiSecret = strategySubscription.ApiKey;
                subscribeAccountInfo.Subscribe(strategyName, accountInfo);
            }
        }
Ejemplo n.º 23
0
 public void Unsubscribe(string strategyName, List <StrategySubscription> strategySubscription, ITradeStrategy tradeStrategy)
 {
     foreach (var subscription in strategySubscription)
     {
         Caches.TryRemove(subscription.Symbol, out _);
     }
 }
 public TradingMarketUpdateDrivenProcess(ILogger logger, ITradeStrategy <Order> orderStrategy)
     : base(logger, orderStrategy)
 {
 }
Ejemplo n.º 25
0
 public TradingHeartBeatDrivenProcess(ILogger logger, ITradeStrategy <Order> orderStrategy, IHeartbeat heartbeat)
     : base(logger, orderStrategy)
 {
     this._heartbeat = heartbeat ?? throw new ArgumentNullException(nameof(heartbeat));
 }
Ejemplo n.º 26
0
 public void Unsubscribe(string strategyName, StrategySubscription strategySubscription, ITradeStrategy tradeStrategy)
 {
     throw new System.NotImplementedException();
 }
Ejemplo n.º 27
0
        private void Unsubscribe(string strategyName, StrategySubscription symbol, string cacheKey, ITradeStrategy tradeStrategy)
        {
            if (Caches.TryGetValue(cacheKey, out ISubscriptionCache cache))
            {
                cache.Unsubscribe(strategyName, symbol, tradeStrategy);

                if (!cache.HasSubscriptions)
                {
                    if (Caches.TryRemove(cacheKey, out ISubscriptionCache cacheDispose))
                    {
                        cacheDispose.Dispose();
                    }
                }
            }
        }
Ejemplo n.º 28
0
 public ResponseTradeMessage(ITradeStrategy strategy) : base(strategy.Id)
 {
     Strategy = strategy;
 }
Ejemplo n.º 29
0
 public bool TryGetTradeStrategy(string strategyName, out ITradeStrategy tradeStrategy)
 {
     return(tradeStrategies.TryGetValue(strategyName, out tradeStrategy));
 }