예제 #1
0
        private void OnOrderExecuted(Execution execution)
        {
            var instrument = Securities.FirstOrDefault(i => i.SecurityId == execution.Order.InstrumentId);

            if (instrument != null)
            {
                ProcessOrderExecution(Converter.ToCommonOrder(execution, instrument.Symbol, Name));
            }
        }
예제 #2
0
        private void OnOrderChanged(Com.Lmax.Api.Order.Order order)
        {
            var instrument = Securities.FirstOrDefault(i => i.SecurityId == order.InstrumentId);

            if (instrument != null)
            {
                ProcessOrderChange(Converter.ToCommonOrder(order, instrument.Symbol, Name));
            }
        }
예제 #3
0
        private void OnInstructionRejected(InstructionRejectedEvent rejected)
        {
            var instrument = Securities.FirstOrDefault(i => i.SecurityId == rejected.InstrumentId);

            if (instrument != null)
            {
                OnOrderRejected(new Order(rejected.InstructionId, instrument.Symbol)
                {
                    AccountId  = AccountInfo.ID,
                    BrokerName = Name
                }, rejected.Reason);
            }
        }
예제 #4
0
        private void OnInstructionFailed(object sender, Tuple <OrderSpecification, string> failed)
        {
            var instrument = Securities.FirstOrDefault(i => i.SecurityId == failed.Item1.InstrumentId);

            if (instrument != null)
            {
                var order = new Order(failed.Item1.InstructionId, instrument.Symbol)
                {
                    AccountId  = AccountInfo.ID,
                    BrokerName = Name,
                    Quantity   = failed.Item1.Quantity,
                    SLOffset   = failed.Item1.StopLossPriceOffset,
                    TPOffset   = failed.Item1.StopProfitPriceOffset
                };
                OnOrderRejected(order, failed.Item2);
            }
        }
예제 #5
0
        private void OnPositionChanged(PositionEvent position)
        {
            var instrument = Securities.FirstOrDefault(i => i.SecurityId == position.InstrumentId);

            if (instrument == null)
            {
                return;
            }

            var positionDetails = new Position(instrument.Symbol)
            {
                PositionSide = position.OpenQuantity > 0 ? Side.Buy : Side.Sell,
                Price        = position.OpenQuantity != 0m
                    ? Math.Abs(position.OpenCost / position.OpenQuantity) / instrument.ContractSize : 0,
                Quantity = position.OpenQuantity
            };

            ProcessPositionUpdate(positionDetails);
        }
예제 #6
0
        public override void ModifyOrder(Order order, decimal?sl, decimal?tp, bool isServerSide = false)
        {
            var tradingError = CheckIfCanTrade();

            if (tradingError != null)
            {
                OnOrderRejected(order, tradingError);
                return;
            }

            var isExisitingOrder = false;

            lock (Orders)
                isExisitingOrder = Orders.Contains(order);

            var unmodified = order.Clone() as Order;

            base.ModifyOrder(order, sl, tp, isServerSide);

            var security = Securities.FirstOrDefault(i => i.Symbol.Equals(order.Symbol, IgnoreCase));

            if (security == null || security.SecurityId < 1)
            {
                return;
            }

            if (isServerSide && isExisitingOrder && !unmodified.ServerSide && unmodified.OpenQuantity > 0 &&
                (unmodified.SLOffset.HasValue || unmodified.TPOffset.HasValue))
            {
                _session.AmendStops(new AmendStopLossProfitRequest(security.SecurityId,
                                                                   unmodified.UserID + "_m", unmodified.UserID, null, null), id => { }, GeneralFailureCallback);
            }
            else if (!isServerSide && unmodified.OpenQuantity > 0 && (sl.HasValue || tp.HasValue))
            {
                _session.AmendStops(new AmendStopLossProfitRequest(security.SecurityId,
                                                                   unmodified.UserID + "_m", unmodified.UserID, sl, tp), id => { }, GeneralFailureCallback);
            }
        }
예제 #7
0
        public override void CancelOrder(Order order)
        {
            var tradingError = CheckIfCanTrade();

            if (tradingError != null)
            {
                OnOrderRejected(order, tradingError);
                return;
            }

            if (order.ServerSide)
            {
                base.CancelOrder(order);
            }
            else
            {
                var security = Securities.FirstOrDefault(i => i.Symbol.Equals(order.Symbol, IgnoreCase));
                if (security != null)
                {
                    _session.CancelOrder(new CancelOrderRequest(order.UserID + "_c",
                                                                security.SecurityId, order.UserID), id => { }, GeneralFailureCallback);
                }
            }
        }
예제 #8
0
            protected override void OnProcessMessage(Message message, MessageDirections direction)
            {
                //_historyMessageAdapter.UpdateCurrentTime(message.LocalTime);

                switch (message.Type)
                {
                case MessageTypes.Connect:
                {
                    if (message.Adapter == MarketDataAdapter)
                    {
                        break;
                    }

                    _isHistory        = true;
                    _isInitialization = true;
                    _connectTime      = message.LocalTime;
                    _strategy.SetIsInitialization(true);

                    _historyMessageAdapter
                    .SecurityProvider
                    .LookupAll()
                    .ForEach(s => SendOutMessage(s.ToMessage()));

                    break;
                }

                case (MessageTypes)(-1):
                {
                    new ChartAutoRangeCommand(false).Process(_strategy);

                    _strategy.PositionManager.Positions = _sessionStrategy.Positions.Select(p => p.Position).ToList();

                    if (_onlyInitialize)
                    {
                        if (message.Adapter == MarketDataAdapter)
                        {
                            new StopStrategyCommand(_strategy).Process(this);
                        }

                        return;
                    }

                    _historyMessageAdapter.StopDate = DateTimeOffset.MaxValue;
                    _historyMessageAdapter.MarketTimeChangedInterval = TimeSpan.FromMilliseconds(10);

                    var messages = new List <Message>();

                    messages.AddRange(_realConnector.Trades.Select(t => t.ToMessage()));
                    messages.AddRange(_realConnector.Orders.Select(o => o.ToMessage()));
                    messages.AddRange(_realConnector.OrderRegisterFails.Select(o => o.ToMessage()));
                    messages.AddRange(_realConnector.OrderCancelFails.Select(o => o.ToMessage()));
                    messages.AddRange(_realConnector.MyTrades.Select(t => t.ToMessage()));

                    messages.ForEach(SendOutMessage);

                    _isHistory = false;

                    return;
                }

                case MessageTypes.Execution:
                {
                    var execMsg = (ExecutionMessage)message;

                    if (execMsg.ExecutionType == ExecutionTypes.Tick && !_isHistory && _isInitialization)
                    {
                        ProcessTime(execMsg.ServerTime, execMsg.SecurityId.BoardCode);
                    }

                    break;
                }

                default:
                {
                    var candleMsg = message as CandleMessage;

                    if (candleMsg == null)
                    {
                        break;
                    }

                    if (!_isHistory)
                    {
                        break;
                    }

                    var stocksharpId = CreateSecurityId(candleMsg.SecurityId.SecurityCode, candleMsg.SecurityId.BoardCode);
                    var security     = Securities.FirstOrDefault(s => s.Id.CompareIgnoreCase(stocksharpId));

                    if (security == null)
                    {
                        throw new InvalidOperationException(LocalizedStrings.Str704Params.Put(candleMsg.SecurityId));
                    }

                    var volumeStep = security.VolumeStep ?? 1m;
                    var decimals   = volumeStep.GetCachedDecimals();

                    var trades = candleMsg.ToTrades(volumeStep, decimals);

                    foreach (var executionMessage in trades)
                    {
                        base.OnProcessMessage(executionMessage, direction);
                    }

                    return;
                }
                }

                base.OnProcessMessage(message, direction);
            }
예제 #9
0
        public void GetHistory(Selection parameters, HistoryAnswerHandler callback)
        {
            if (_session == null)
            {
                throw new ApplicationException("Can't load history. LMAX data feed is not connected.");
            }

            var symbol     = parameters.Symbol.ToUpper();
            var instrument = Securities.FirstOrDefault(i => i.Symbol.Equals(symbol, StringComparison.OrdinalIgnoreCase));

            if (instrument == null)
            {
                Logger.Warning($"Invalid symbol {parameters.Symbol} passed for history request over {Name} feed");
                return;
            }

            lock (_historyRequestHandlers)
            {
                if (parameters.To == DateTime.MinValue || parameters.To > DateTime.UtcNow)
                {
                    parameters.To = DateTime.UtcNow;
                }

                //calculate start time
                if (parameters.From == DateTime.MinValue && parameters.BarCount != int.MaxValue)
                {
                    if (parameters.BarCount < 3)
                    {
                        callback(parameters, new List <Bar>());
                        return;
                    }

                    if (parameters.To > DateTime.UtcNow)
                    {
                        parameters.To = DateTime.UtcNow;
                    }

                    if (parameters.Timeframe == Timeframe.Minute)
                    {
                        parameters.From = parameters.To.AddMinutes(-1 * 3 * parameters.BarCount * parameters.TimeFactor);
                    }
                    else if (parameters.Timeframe == Timeframe.Hour)
                    {
                        parameters.From = parameters.To.AddHours(-1 * 3 * parameters.BarCount * parameters.TimeFactor);
                    }
                    else if (parameters.Timeframe == Timeframe.Day)
                    {
                        parameters.From = parameters.To.AddDays(-1 * 2 * parameters.BarCount * parameters.TimeFactor);
                    }
                    else if (parameters.Timeframe == Timeframe.Month)
                    {
                        parameters.From = parameters.To.AddDays(-1 * parameters.BarCount * parameters.TimeFactor * 31);
                    }
                }

                parameters.From = TimeZoneInfo.ConvertTimeFromUtc(parameters.From, TimeZoneInfo);
                parameters.To   = TimeZoneInfo.ConvertTimeFromUtc(parameters.To, TimeZoneInfo);

                var bidParams = (Selection)parameters.Clone();
                bidParams.BidAsk = PriceType.Bid;
                var id = ++_id;
                _historyRequestHandlers.Add(id, callback);
                _originalHistoryRequestParameters.Add(id, bidParams);

                _session?.RequestHistoricMarketData(new AggregateHistoricMarketDataRequest(id, instrument.SecurityId, bidParams.From, bidParams.To,
                                                                                           FromPeriodToResolution(bidParams.Timeframe), Format.Csv, Option.Bid), () => { }, FailureCallback);

                var askParams = (Selection)parameters.Clone();
                askParams.BidAsk = PriceType.Ask;
                id = ++_id;
                _historyRequestHandlers.Add(id, callback);
                _originalHistoryRequestParameters.Add(id, askParams);

                _session?.RequestHistoricMarketData(new AggregateHistoricMarketDataRequest(id, instrument.SecurityId, askParams.From, askParams.To,
                                                                                           FromPeriodToResolution(askParams.Timeframe), Format.Csv, Option.Ask), () => { }, FailureCallback);

                //

                /*var askHistParams = (Selection)parameters.Clone();
                 * askHistParams.BidAsk = PriceType.Unspecified;
                 * id = ++_id;
                 * _historyRequestHandlers.Add(id, callback);
                 * _originalHistoryRequestParameters.Add(id, askHistParams);
                 *
                 * _session?.RequestHistoricMarketData(new TopOfBookHistoricMarketDataRequest(id, instrument.SecurityId, askParams.From, askParams.To, Format.Csv),
                 *  () => { }, FailureCallback);*/
            }
        }
예제 #10
0
        private void InitializeWatchlist(string name)
        {
            SecList = new ObservableCollection <Security>();
            Name    = name;
            var xml  = new XmlSerializer(typeof(List <Security>));
            var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
                       "\\Inside MMA\\settings\\watchlists\\" + name;

            WatchListPath = path;
            List <Security> list = new List <Security>();

            try
            {
                using (
                    var file =
                        File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    list = (List <Security>)xml.Deserialize(file);
                }
            }
            catch
            {
            }
            string error = string.Empty;

            foreach (var security in list)
            {
                if (Securities.FirstOrDefault(s => s.Seccode == security.Seccode) != null)
                {
                    SecList.Add(security);
                }
                else
                {
                    error += security.Seccode + ",";
                }
            }
            if (error != string.Empty)
            {
                Task.Run(() =>
                {
                    SpinWait.SpinUntil(() => Dialog != null);
                    Dialog.ShowMessageAsync(this, "Warning",
                                            "The following instruments were not found: " + error.TrimEnd(','));
                    var serializer = new XmlSerializer(typeof(List <Security>));
                    using (var file = File.Open(WatchListPath, FileMode.Open, FileAccess.ReadWrite))
                    {
                        var data = (List <Security>)serializer.Deserialize(file);
                        foreach (var s in error.Split(','))
                        {
                            data.RemoveWhere(sec => sec.Seccode == s);
                        }
                        file.SetLength(0);
                        serializer.Serialize(file, data);
                        file.Close();
                    }
                });
            }
            //Task.Run(() =>
            ////{
            ////    if (_firstBoot)
            ////        Thread.Sleep(3000);
            //    TickDataHandler.WatchlistSub(SecList.ToList());
            //});
            TickDataHandler.WatchlistSub(SecList.ToList());
        }