コード例 #1
0
        public RequestStatus SendNewOrderRequest(Account account,
                                                 MarketOrder order,
                                                 OrderType orderType,
                                                 decimal requestedPrice,
                                                 decimal slippagePoints)
        {
            TradeSharp.ProviderProxyContract.Entity.MarketOrder request;
            RequestStatus error;

            if (!MakeMarketRequest(account, order.Symbol, order.Magic, order.Volume, order.Side,
                                   orderType,
                                   requestedPrice, slippagePoints,
                                   string.Format("open for acc#{0}", account.ID),
                                   null, order.Comment, order.ExpertComment, order.trailingLevels[0], order.trailingTargets[0],
                                   out error, out request))
            {
                return(error);
            }

            // отправить запрос на вход в рынок в соотв сессию
            if (!request.SendToQueue(false))
            {
                errorStorage.AddMessage(new ErrorMessage(DateTime.Now, ErrorMessageType.ОшибкаОтправки,
                                                         "Невозможно отправить сообщение (NewOrder) в очередь MQ", null));
                return(RequestStatus.DealerError);
            }
            return(RequestStatus.OK);
        }
コード例 #2
0
        public RequestStatus SendCloseRequest(MarketOrder order, PositionExitReason reason)
        {
            // получить счет
            RequestStatus error;
            var           acDecorated = ServerInterface.GetAccount(order.AccountID);

            if (acDecorated == null)
            {
                return(RequestStatus.ServerError);
            }

            // подготовить запрос
            TradeSharp.ProviderProxyContract.Entity.MarketOrder request;
            if (!MakeMarketRequest(acDecorated, order.Symbol, order.Magic, order.Volume, -order.Side,
                                   OrderType.Market,
                                   0, 0,
                                   string.Format("close order #{0}", order.ID),
                                   order.ID, order.Comment, order.ExpertComment, order.TrailLevel1, order.TrailTarget1,
                                   out error, out request))
            {
                return(error);
            }
            exitReasonByOrderId.UpdateValues(order.ID, reason);

            // отправить запрос на вход в рынок (оно же - закрытие позиции) в соотв сессию
            if (!request.SendToQueue(false))
            {
                errorStorage.AddMessage(new ErrorMessage(DateTime.Now, ErrorMessageType.ОшибкаОтправки,
                                                         "Невозможно отправить сообщение (CloseOrder) в очередь MQ", null));
                return(RequestStatus.DealerError);
            }
            return(RequestStatus.OK);
        }
コード例 #3
0
        public void CalculateDealVolumeInDepoCurrency()
        {
            const int volume = 10000;
            var deal = new MarketOrder
            {
                Symbol = "USDRUB",
                Volume = volume,
                Side = 1,
                PriceEnter = 1.3290f,
                TimeEnter = DateTime.Now.AddMinutes(-60 * 24 * 3),
                State = PositionState.Opened,
                ExpertComment = "",
                MasterOrder = 10001
            };
            var dicQuote = new Dictionary<string, List<QuoteData>>();
            var quoteArc = new QuoteArchive(dicQuote);

            curveCalculator.CalculateDealVolumeInDepoCurrency(deal, new QuoteData(1.3820f, 1.3822f, DateTime.Now), "USD", quoteArc, DateTime.Now);
            Assert.AreEqual(0, deal.VolumeInDepoCurrency, "При разных валютах депозита и сделки и не инициализированом словаре котировок, метод не вернул правильное значение");

            curveCalculator.CalculateDealVolumeInDepoCurrency(deal, new QuoteData(1.3820f, 1.3822f, DateTime.Now), "RUB", quoteArc, DateTime.Now);
            Assert.AreEqual(volume * (1.3822f + 1.3820f) / 2, deal.VolumeInDepoCurrency,
                "При одинаковых валютах депозита и сделки метод не вернул правильное значение");

            foreach (var smb in DalSpot.Instance.GetTickerNames())
                dicQuote.Add(smb, dailyQuoteStorage.GetQuotes(smb).Select(q => new QuoteData(q.b, q.b, q.a)).ToList());
            quoteArc = new QuoteArchive(dicQuote);

            curveCalculator.CalculateDealVolumeInDepoCurrency(deal, new QuoteData(1.3820f, 1.3822f, DateTime.Now), "RUB", quoteArc, dicQuote["USDRUB"].First().time);
            Assert.AreEqual(volume * (1.3822f + 1.3820f) / 2, deal.VolumeInDepoCurrency,
                "При инициализированных всех данных и метод не вернул правильное значение");
        }
コード例 #4
0
 private bool IsOverflooded(TradeTransactionRequest request, MarketOrder order)
 {
     try
     {
         var isFlooded = RequestStorage.Instance.CheckOverflood();
         if (isFlooded)
         {
             var errorResponse = new BrokerService.Contract.Entity.BrokerResponse
             {
                 AccountId          = request.Account,
                 Mt4OrderId         = request.ClosingPositionId ?? 0,
                 RejectReason       = OrderRejectReason.UnableMassCancel,
                 Status             = OrderStatus.Rejected,
                 RejectReasonString = "overflood",
                 RequestId          = request.Id,
                 ValueDate          = DateTime.Now
             };
             ServerInterface.NotifyClientOnOrderRejected(order, errorResponse.RejectReasonString);
             return(true);
         }
     }
     catch (Exception ex)
     {
         Logger.Error("Error in CheckOverflood()", ex);
         return(true);
     }
     return(false);
 }
コード例 #5
0
ファイル: SignalDealer.cs プロジェクト: johnmensen/TradeSharp
 public RequestStatus SendCloseRequest(MarketOrder order, PositionExitReason reason)
 {
     if (string.IsNullOrEmpty(order.ExpertComment))
     {
         Logger.ErrorFormat("SignalDealer.SendCloseRequest({0}) - поле ExpertComment не заполнено",
             order.ID);
         //return RequestStatus.DealerError;
     }
     // получить цену
     var quote = QuoteStorage.Instance.ReceiveValue(order.Symbol);
     if (quote == null)
         return RequestStatus.NoPrice;
     var price = order.Side > 0 ? quote.GetPrice(QuoteType.Bid) : quote.GetPrice(QuoteType.Ask);
     // отправить сигнал
     var signal = new ManagerSignal {Id = order.ExpertComment, PriceClose = (decimal)price, Category = signalCategoryCode,
         Symbol = order.Symbol, Leverage = 0, Price = (decimal)order.PriceEnter, Side = order.Side};
     var timeExec = new ThreadSafeTimeStamp();
     timeExec.Touch();
     if (!string.IsNullOrEmpty(order.ExpertComment) && !SendSignal(signal, false))
         return RequestStatus.DealerError;
     var endTime = DateTime.Now - timeExec.GetLastHit();
     Logger.InfoFormat("Время исполнения SendCloseRequest SendSignal: {0} секунд, {1} миллисекунд", endTime.TotalSeconds, endTime.TotalMilliseconds);
     timeExec.Touch();
     // закрыть ордер немедленно
     var result = ServerInterface.CloseOrder(order, (decimal) price, reason);
     endTime = DateTime.Now - timeExec.GetLastHit();
     Logger.InfoFormat("Время исполнения SendCloseRequest - CloseOrder: {0} секунд, {1} миллисекунд", endTime.TotalSeconds, endTime.TotalMilliseconds);
     return result ? RequestStatus.OK : RequestStatus.ServerError;
 }
コード例 #6
0
 private string SerializeClosedDeal(MarketOrder deal)
 {
     return string.Format(
         "insert into POSITION_CLOSED (ExitReason, Symbol, Side, AccountID, Volume," +
         "Comment, ExpertComment, Stoploss, Takeprofit, Magic, PriceEnter, TimeEnter, " +
         "PriceExit, TimeExit, Swap, ResultPoints, ResultBase, ResultDepo) VALUES " +
         "({0}, '{1}', {2}, {3}, {4}, " +
         "'{5}', '{6}', '{7}', '{8}', {9}, '{10}', '{11}', " +
         "'{12}', '{13}', '{14}', '{15}', '{16}', '{17}')",
         (int)deal.State,
         deal.Symbol,
         deal.Side,
         deal.AccountID,
         deal.Volume,
         deal.Comment,
         deal.ExpertComment,
         deal.StopLoss.HasValue ? deal.StopLoss.Value.ToStringUniformPriceFormat(true) : "",
         deal.TakeProfit.HasValue ? deal.TakeProfit.Value.ToStringUniformPriceFormat(true) : "",
         deal.Magic,
         deal.PriceEnter.ToStringUniformPriceFormat(),
         deal.TimeEnter.ToString("yyyyMMdd HH:mm"),
         deal.PriceExit.Value.ToStringUniformPriceFormat(),
         deal.TimeExit.Value.ToString("yyyyMMdd HH:mm"),
         0,
         deal.ResultPoints.ToStringUniformMoneyFormat(),
         deal.ResultBase.ToStringUniformMoneyFormat(),
         deal.ResultDepo.ToStringUniformMoneyFormat());
 }
コード例 #7
0
ファイル: Mt4Dealer.cs プロジェクト: rafysanchez/TradeSharp
        public RequestStatus SendCloseRequest(MarketOrder order, PositionExitReason reason)
        {
            var requestedPrice = 0M;
            var quote          = QuoteStorage.Instance.ReceiveValue(order.Symbol);

            if (quote != null)
            {
                requestedPrice = (decimal)(order.Side > 0 ? quote.bid : quote.ask);
            }

            if (!order.MasterOrder.HasValue)
            {
                Logger.DebugFormat("{0}: SendCloseRequest - закрытие ордера {1} - MasterOrder не задан",
                                   DealerCode, order.ToStringShort());
                return(RequestStatus.DealerError);
            }

            var status = MakeMarketRequest(new TradeTransactionRequest
            {
                Account           = order.AccountID,
                ClosingPositionId = order.MasterOrder,
                Comment           = order.Comment,
                ExpertComment     = order.ExpertComment,
                Id             = order.ID,
                Magic          = order.Magic,
                RequestedPrice = requestedPrice,
                SlippageAbs    = 0,
                Side           = order.Side,
                Symbol         = order.Symbol,
                Volume         = order.Volume
            }, order);

            return(status);
        }
コード例 #8
0
ファイル: DemoDealer.cs プロジェクト: johnmensen/TradeSharp
        public virtual RequestStatus SendNewOrderRequest(Account account,
            MarketOrder order,
            OrderType orderType,
            decimal requestedPrice,
            decimal slippagePoints)
        {
            order.State = PositionState.Opened;
            order.TimeEnter = DateTime.Now;

            //if (magic.HasValue)
            //    order.ExpertComment = comment;
            //else
            //    order.Comment = comment;
            // подставить текущую цену
            var quote = QuoteStorage.Instance.ReceiveValue(order.Symbol);
            if (quote == null)
                return RequestStatus.NoPrice;
            order.PriceEnter = order.Side > 0 ? quote.ask : quote.bid;
            // проверить проскальзывание
            if (slippagePoints != 0)
            {
                var slippageAbs = DalSpot.Instance.GetAbsValue(order.Symbol, slippagePoints);
                var delta = Math.Abs(order.PriceEnter - (float)requestedPrice);
                if (delta > (float)slippageAbs) return RequestStatus.Slippage;
            }

            int posID;
            // сохранить ордер (и уведомить клиента)
            var result = ServerInterface.SaveOrderAndNotifyClient(order, out posID);
            return result ? RequestStatus.OK : RequestStatus.SerializationError;
        }
コード例 #9
0
ファイル: PositionForm.cs プロジェクト: johnmensen/TradeSharp
        public PositionForm(MarketOrder order)
        {
            InitializeComponent();

            this.order = order;
            SetupForm();
            ShowOrderParams();
        }
コード例 #10
0
 public override RequestStatus ModifyMarketOrderRequest(MarketOrder order)
 {
     var status = ServerInterface.ModifyMarketOrder(order)
         ? RequestStatus.OK : RequestStatus.ServerError;
     if (status == RequestStatus.OK)
         SendRequest(order, "modify");
     return status;
 }
コード例 #11
0
        /// <summary>
        /// добавить маркапы и прочее шкурилово
        /// </summary>
        public static void ProcessOrderClosing(MarketOrder order,
            ACCOUNT account,
            ORDER_BILL bill, 
            TradeSharpConnection ctx,
            Dictionary<string, QuoteData> quotes, string brokerCurrency)
        {
            //Logger.Info("BillingManager.ProcessOrderClosing()");
            try
            {
                // перевести маркапы в валюту брокера
                var markupSum = bill.MarkupExit + bill.MarkupEnter;
                // в контрвалюте...
                if (markupSum != 0)
                    markupSum = order.Volume * markupSum;
                Logger.Info("BillingManager: markupSum is " + markupSum);

                // перевести в валюту брокера
                var resultCounter = order.Side * order.Volume * (order.PriceExit.Value - order.PriceEnter);
                var rateCounterDepo = resultCounter == 0 ? 1 : order.ResultDepo / resultCounter;
                // валюта брокера к контрвалюте
                var rateCounterBroker = rateCounterDepo;
                Logger.Info("BillingManager: rateCounterDepo is " + rateCounterDepo);

                if (account.Currency != brokerCurrency)
                {
                    // пример: позиция EURCAD, валюта брокера USD
                    // надо получить курс CADUSD
                    var markupBroker = (float) markupSum;
                    string errorStr;
                    var resultedMarkup = DalSpot.Instance.ConvertToTargetCurrency(order.Symbol, false, brokerCurrency,
                                                                            markupBroker, quotes, out errorStr, true);

                    if (!resultedMarkup.HasValue)
                    {
                        Logger.ErrorFormat("BillingManager.ProcessOrderClosing - невозможно перевести профит по {0} в {1}: {2}",
                            order.Symbol, brokerCurrency, errorStr);
                        return;
                    }
                    markupBroker = (float)resultedMarkup.Value;
                    rateCounterBroker = (float)(markupBroker / markupSum);
                    markupSum = markupBroker;
                }
                else
                    markupSum *= rateCounterBroker;
                bill.MarkupBroker = markupSum;
                bill.ProfitBroker = resultCounter * rateCounterBroker;
                Logger.InfoFormat("BillingManager: MarkupBroker: {0}, ProfitBroker: {1}",
                    bill.MarkupBroker, bill.ProfitBroker);

                // сохранить билль
                ctx.Entry(bill).State = EntityState.Modified;
                Logger.InfoFormat("BillingManager:OK");
            }
            catch (Exception ex)
            {
                Logger.Error("BillingManager.ProcessOrderClosing() - ошибка редактирования счета", ex);
            }
        }
コード例 #12
0
 public void NewCloseOrderResponse(MarketOrder order, RequestStatus status, string detailMessage)
 {
     if (status == RequestStatus.OK)
         logMessage(string.Format("Счет {0}: ордер {1} закрыт",
                                  order.AccountID, order));
     else
         logMessage(string.Format("Счет {0}: ошибка закрытия ордера {1}: {2}",
                                  order.AccountID, order, status));
 }
コード例 #13
0
 public void EditOrderResponse(MarketOrder order, RequestStatus status, string detailMessage)
 {
     if (status == RequestStatus.OK)
         logMessage(string.Format("Счет {0}: ордер {1} успешно изменен",
                                  order.AccountID, order));
     else
         logMessage(string.Format("Счет {0}: ошибка редактирования ордера {1}: {2}",
                                  order.AccountID, order, status));
 }
コード例 #14
0
 public bool ProcessOrders(MarketOrder[] posList)
 {
     if (onPositionsReceived != null)
     {
         onPositionsReceived(posList);
         return true;
     }
     return false;
 }
コード例 #15
0
ファイル: DemoDealer.cs プロジェクト: johnmensen/TradeSharp
        public virtual RequestStatus SendCloseRequest(MarketOrder order, PositionExitReason reason)
        {
            // получить цену
            var quote = QuoteStorage.Instance.ReceiveValue(order.Symbol);
            if (quote == null)
                return RequestStatus.NoPrice;
            var price = order.Side > 0 ? quote.GetPrice(QuoteType.Bid) : quote.GetPrice(QuoteType.Ask);

            // закрыть ордер немедленно
            return ServerInterface.CloseOrder(order, (decimal)price, reason)
                ? RequestStatus.OK : RequestStatus.ServerError;
        }
コード例 #16
0
 public void NewOrderResponse(MarketOrder order, RequestStatus status, string detailMessage)
 {
     if (status == RequestStatus.OK)
         logMessage(string.Format("Счет {0}: ордер ({1} {2} {3}) успешно размещен",
                                  order.AccountID, order.Side > 0 ? "BUY" : "SELL",
                                  order.Volume.ToStringUniformMoneyFormat(), order.Symbol));
     else
         logMessage(string.Format("Счет {0}: ошибка размещения ордера ({1} {2} {3}): {4}",
                                  order.AccountID, order.Side > 0 ? "BUY" : "SELL",
                                  order.Volume.ToStringUniformMoneyFormat(), order.Symbol,
                                  status));
 }
コード例 #17
0
        public static MarketOrder DeserializeOrder(SerializationReader reader)
        {
            var deal = new MarketOrder
            {
                ID = reader.ReadInt32(),
                AccountID = reader.ReadInt32(),
                Comment = reader.ReadString(),
                ExitReason = (PositionExitReason)reader.ReadInt16(),
                ExpertComment = reader.ReadString(),
                PriceEnter = reader.ReadSingle(),
                ResultDepo = reader.ReadSingle(),
                ResultPoints = reader.ReadSingle(),
                Side = reader.ReadSByte(),
                State = (PositionState) reader.ReadInt16(),
                Symbol = reader.ReadString(),
                TimeEnter = reader.ReadDateTime(),
                Trailing = reader.ReadString(),
                Volume = reader.ReadInt32(),
                VolumeInDepoCurrency = reader.ReadSingle()
            };

            // nullable values
            var flags = reader.ReadOptimizedBitVector32();

            if (flags[magicIsValued])
                deal.Magic = reader.ReadInt32();

            if (flags[pendingOrderIdIsValued])
                deal.PendingOrderID = reader.ReadInt32();

            if (flags[priceBestIsValued])
                deal.PriceBest = reader.ReadSingle();

            if (flags[priceExitIsValued])
                deal.PriceExit = reader.ReadSingle();

            if (flags[priceWorstIsValued])
                deal.PriceWorst = reader.ReadSingle();

            if (flags[stopLossIsValued])
                deal.StopLoss = reader.ReadSingle();

            if (flags[swapIsValued])
                deal.Swap = reader.ReadSingle();

            if (flags[takeProfitIsValued])
                deal.TakeProfit = reader.ReadSingle();

            if (flags[timeExitIsValued])
                deal.TimeExit = reader.ReadDateTime();

            return deal;
        }
コード例 #18
0
ファイル: PositionItem.cs プロジェクト: johnmensen/TradeSharp
        /// <summary>
        /// Конструктор преобразования MarketOrder в PositionItem
        /// </summary>
        public PositionItem(MarketOrder c)
        {
            foreach (var prop in c.GetType().GetProperties())
            {
                var prop2 = c.GetType().GetProperty(prop.Name);
                if (prop2.GetSetMethod() != null)
                    prop2.SetValue(this, prop.GetValue(c, null), null);
            }

            PriceEnter = (decimal) c.PriceEnter;
            PriceExit = (decimal?)c.PriceExit;
            ResultPoints = (decimal?)c.ResultPoints;
            ResultDepo = (decimal?)c.ResultDepo;
        }
コード例 #19
0
 private void ModifyOrders(List<Position> positions, bool closeOrders,
     out int countModified, out int countFailed, out string errors)
 {
     countModified = 0;
     countFailed = 0;
     var errorStrings = new Dictionary<string, string>();
     try
     {
         foreach (var pos in positions)
         {
             string errorString;
             var order = new MarketOrder
             {
                 AccountID = pos.AccountId,
                 ID = pos.Id,
                 Side = pos.Side,
                 Symbol = pos.Symbol,
                 StopLoss = (float)pos.Sl,
                 TakeProfit = (float)pos.Tp,
                 TimeEnter = pos.TimeEnter,
                 Volume = pos.Volume,
                 PriceEnter = (float)pos.PriceEnter,
                 MasterOrder = pos.Mt4Order
             };
             order.State = closeOrders ? PositionState.Closed : PositionState.Opened;
             if (closeOrders)
             {
                 order.TimeExit = pos.TimeExit;
                 order.PriceExit = pos.PriceExit == 0 ? (float?) null : (float) pos.PriceExit;
                 order.ResultDepo = (float) pos.Profit;
             }
             if (PlatformManager.Instance.proxy.ModifyOrder(order, out errorString))
                 countModified++;
             else countFailed++;
             if (!string.IsNullOrEmpty(errorString) && !errorStrings.ContainsKey(errorString))
                 errorStrings.Add(errorString, string.Empty);
         }
         errors = string.Join(". ", errorStrings.Keys);
         Logger.InfoFormat("ModifyOrders({0} orders): {1} are updated, errors: {2}",
             positions.Count, countModified, errors);
     }
     catch (Exception ex)
     {
         countModified = 0;
         countFailed = positions.Count;
         errors = ex.GetType().Name + ": " + ex.Message;
         Logger.ErrorFormat("Error in ModifyOrders({0} orders): {1}",
             positions.Count, ex);
     }
 }
コード例 #20
0
        /// <summary>
        /// добавить маркапы и прочее шкурилово
        /// 
        /// вызывается на открытии рыночного ордера, срабатывании отложенного
        /// (для всех - единая точка входа - SaveOrder & Notify Client)
        /// </summary>
        public static OrderBill ProcessOrderOpening(MarketOrder order, Account account)
        {
            AccountGroup.MarkupType markType;
            var spreadDelta = AcccountMarkupDictionary.GetMarkupAbs(account.Group, order.Symbol, out markType);
            var bill = new OrderBill(0, markType, 0);
            if (spreadDelta > 0 && markType != AccountGroup.MarkupType.NoMarkup)
            {
                if (markType == AccountGroup.MarkupType.Markup)
                    order.PriceEnter += spreadDelta * order.Side;
                bill.MarkupEnter = spreadDelta;
            }

            return bill;
        }
コード例 #21
0
ファイル: Mt4Dealer.cs プロジェクト: rafysanchez/TradeSharp
        private RequestStatus MakeMarketRequest(TradeTransactionRequest request, MarketOrder order)
        {
            Logger.InfoFormat("Отправка запроса в MT4 ({0}): {1}", DealerCode, request);

            try
            {
                RequestStorage.Instance.StoreRequest(new RequestedOrder(request, order));
                rabbitServer.SendRequest(request);
                return(RequestStatus.OK);
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка отправки запроса MT4", ex);
                return(responseNative[BrokerService.Contract.Entity.RequestStatus.ErrorOnExecute]);
            }
        }
コード例 #22
0
        //класс используется при "закрытии" сделок "вручную"
        /// <summary>
        /// для ордера указана цена выхода, но не посчитана прибыль
        /// посчитать прибыль
        /// </summary>
        /// <param name="orderClosed"></param>
        /// <param name="depoCurrency">Валюта депозита</param>
        /// <param name="exitPrice"></param>
        /// <param name="errorStr"></param>
        /// <returns></returns>
        public static bool CalculateOrderProfit(MarketOrder orderClosed, string depoCurrency, float exitPrice, out string errorStr)
        {
            errorStr = string.Empty;

            if (exitPrice <= 0)
            {
                errorStr = "Цена закрытия не может быть меньше либо равной 0";
                return false;
            }

            orderClosed.PriceExit = exitPrice;
            // ReSharper disable PossibleInvalidOperationException
            var resultAbs = orderClosed.Side * (orderClosed.PriceExit.Value - orderClosed.PriceEnter);
            // ReSharper restore PossibleInvalidOperationException
            orderClosed.ResultPoints = DalSpot.Instance.GetPointsValue(orderClosed.Symbol, resultAbs);
            orderClosed.ResultBase = resultAbs * orderClosed.Volume;
            // прибыль в валюте депозита
            bool inverse, areSame;
            var smb = DalSpot.Instance.FindSymbol(orderClosed.Symbol, false, depoCurrency, out inverse, out areSame);
            if (string.IsNullOrEmpty(smb) && !areSame)
            {
                errorStr = "Котировки " + orderClosed + " -> " + depoCurrency + " нет в системе";
                return false;
            }

            var rate = 1f;
            if (!areSame)
            {
                if (smb == orderClosed.Symbol)
                    rate = inverse ? 1 / orderClosed.PriceExit.Value : orderClosed.PriceExit.Value;
                else
                {
                    var quote = QuoteStorage.Instance.ReceiveValue(smb);
                    if (quote == null)
                    {
                        errorStr = "Нет котировки по паре " + smb;
                        return false;
                    }
                    rate = inverse ? 1 / quote.ask : quote.bid;
                }
            }
            orderClosed.ResultDepo = rate * orderClosed.ResultBase;
            return true;
        }
コード例 #23
0
 private static void TryCloseDeal(MarketOrder deal)
 {
     try
     {
         var res = MainForm.serverProxyTrade.proxy.SendCloseRequest(
             CurrentProtectedContext.Instance.MakeProtectedContext(),
             deal.AccountID, deal.ID, PositionExitReason.ClosedBySignal);
         if (res != RequestStatus.OK)
         {
             Logger.ErrorFormat("TradeSignalMonitorStream.CheckOrders() - невозможно закрыть сделку #{0} ({1} {2} {3}) - {4}",
             deal.ID, deal.Side > 0 ? "BUY" : "SELL", deal.Volume, deal.Symbol, res);
         }
     }
     catch (Exception ex)
     {
         Logger.ErrorFormat("TradeSignalMonitorStream.CheckOrders() - ошибка закрытия сделки #{0} ({1} {2} {3}) - {4}",
             deal.ID, deal.Side > 0 ? "BUY" : "SELL", deal.Volume, deal.Symbol, ex);
     }
 }
コード例 #24
0
 private string SerializeOpenedDeal(MarketOrder deal)
 {
     return string.Format(
         "insert into POSITION (State, Symbol, Side, AccountID, Volume," +
         "Comment, ExpertComment, Stoploss, Takeprofit, Magic, PriceEnter, TimeEnter) VALUES " +
         "({0}, '{1}', {2}, {3}, {4}, " +
         "'{5}', '{6}', '{7}', '{8}', {9}, '{10}', '{11}')",
         (int) deal.State,
         deal.Symbol,
         deal.Side,
         deal.AccountID,
         deal.Volume,
         deal.Comment,
         deal.ExpertComment,
         deal.StopLoss.HasValue ? deal.StopLoss.Value.ToStringUniformPriceFormat() : "",
         deal.TakeProfit.HasValue ? deal.TakeProfit.Value.ToStringUniformPriceFormat() : "",
         deal.Magic,
         deal.PriceEnter.ToStringUniformPriceFormat(),
         deal.TimeEnter.ToString("yyyyMMdd HH:mm"));
 }
コード例 #25
0
        /// <summary>
        /// Расчитать объем сделки в валюте депозита
        /// </summary>
        public void CalculateDealVolumeInDepoCurrency(MarketOrder deal, QuoteData dealQuote, string depoCurrency, QuoteArchive arc, DateTime date)
        {
            var volumeInCounter = deal.Volume * dealQuote.GetPrice(QuoteType.NonSpecified);

            // перевести из контрвалюты в валюту депо
            bool inverse, pairsAreEqual;
            var smb = DalSpot.Instance.FindSymbol(deal.Symbol, false, depoCurrency, out inverse, out pairsAreEqual);
            if (pairsAreEqual)
            {
                deal.VolumeInDepoCurrency = volumeInCounter;
                return;
            }

            if (string.IsNullOrEmpty(smb)) return;
            var quoteCtDepo = arc.GetQuoteOnDateSeq(smb, date);
            if (quoteCtDepo == null) return;
            var priceCtDepo = quoteCtDepo.GetPrice(QuoteType.NonSpecified);
            if (priceCtDepo == 0) return;

            deal.VolumeInDepoCurrency = inverse ? volumeInCounter / priceCtDepo : volumeInCounter * priceCtDepo;
        }
コード例 #26
0
 public static string MakeOrderTitle(MarketOrder order)
 {
     var sb = new StringBuilder();
     sb.AppendLine(string.Format("#{0} {1} {2} по {3}, {4:dd.MM HH:mm:ss}{5}",
                                     order.ID, order.Side > 0 ? "BUY" : "SELL",
                                     order.Volume.ToStringUniformMoneyFormat(),
                                     DalSpot.Instance.FormatPrice(
                                         order.Symbol, order.PriceEnter),
                                         order.TimeEnter, order.PriceExit.HasValue
                                         ? "," : ""));
     if (order.PriceExit.HasValue)
     {
         sb.AppendLine(string.Format("закрыта по {0} {1:dd.MM HH:mm:ss}\n" +
             "Результат (пп - депо.): {2} / {3}",
         // ReSharper disable PossibleInvalidOperationException
                                     order.PriceExit.Value, order.TimeExit.Value,
                                     (int)order.ResultPoints,
                                     (int)order.ResultDepo));
         // ReSharper restore PossibleInvalidOperationException
     }
     return sb.ToString();
 }
コード例 #27
0
        private void CheckScriptTriggerOrder(ScriptTriggerDealEventType evt, MarketOrder order)
        {
            // сформировать список скриптов для срабатывания
            var scriptsToFire = new List<TerminalScript>();
            var scripts = ScriptManager.Instance.GetScripts().ToList();
            foreach (var script in scripts.Where(s => s.Trigger != null &&
                s.Trigger is ScriptTriggerDealEvent /*&& s.ScriptTarget != TerminalScript.TerminalScriptTarget.График*/))
            {
                var orderScriptTrigger = (ScriptTriggerDealEvent)script.Trigger;
                var shouldFire = (orderScriptTrigger.eventType & evt) == evt;
                if (shouldFire)
                {
                    orderScriptTrigger.sourceOrder = order;
                    orderScriptTrigger.sourceEvent = evt;
                    scriptsToFire.Add(script);
                }
            }

            // запустить скрипты на выполнение
            if (scriptsToFire.Count > 0)
                ThreadPool.QueueUserWorkItem(ExecuteScriptsRoutine, scriptsToFire);
        }
コード例 #28
0
ファイル: Mt4Dealer.cs プロジェクト: rafysanchez/TradeSharp
        public RequestStatus SendNewOrderRequest(Account account,
                                                 MarketOrder order,
                                                 OrderType orderType,
                                                 decimal requestedPrice,
                                                 decimal slippagePoints)
        {
            var quote = QuoteStorage.Instance.ReceiveValue(order.Symbol);

            if (quote == null)
            {
                return(RequestStatus.NoPrice);
            }

            var slippageAbs = slippagePoints;

            if (slippageAbs > 0)
            {
                slippageAbs = DalSpot.Instance.GetAbsValue(order.Symbol, slippageAbs);
            }
            var status = MakeMarketRequest(new TradeTransactionRequest
            {
                Account           = account.ID,
                ClosingPositionId = null,
                Comment           = order.Comment,
                ExpertComment     = order.ExpertComment,
                Id             = RequestUniqueId, // !!
                Magic          = order.Magic,
                RequestedPrice = (decimal)(order.Side > 0 ? quote.ask : quote.bid),
                SlippageAbs    = slippageAbs,
                Side           = order.Side,
                Symbol         = order.Symbol,
                Volume         = order.Volume
            }, order);

            return(status);
        }
コード例 #29
0
ファイル: BaseRobot.cs プロジェクト: johnmensen/TradeSharp
 /// <summary>
 /// Send market or instant order
 /// </summary>
 /// <param name="order">все параметры ордера</param>
 /// <param name="ordType"></param>
 /// <param name="slippagePoints"></param>        
 /// <returns></returns>
 protected RequestStatus NewOrder(MarketOrder order, OrderType ordType, 
     decimal requestedPrice, decimal slippagePoints)
 {
     order.Magic = magic;
     order.AccountID = robotContext.AccountInfo.ID;
     return robotContext.SendNewOrderRequest(
         protectedContext.MakeProtectedContext(),
         RequestUniqueId.Next(),
         order,
         ordType, requestedPrice, slippagePoints);
 }
コード例 #30
0
ファイル: BaseRobot.cs プロジェクト: johnmensen/TradeSharp
 /// <summary>
 /// Change parameters for market 
 /// </summary>
 /// <param name="pos"></param>
 /// <returns></returns>
 protected RequestStatus ModifyMarketOrder(MarketOrder pos)
 {
     return robotContext.SendEditMarketRequest(protectedContext.MakeProtectedContext(), pos);
 }
コード例 #31
0
ファイル: BaseRobot.cs プロジェクト: johnmensen/TradeSharp
 protected float GetPointsDeviation(MarketOrder order, float newValue, bool stopLoss)
 {
     var value = stopLoss ? order.StopLoss : order.TakeProfit;
     if (!value.HasValue)
         return 0;
     var pointsValue = DalSpot.Instance.GetPointsValue(order.Symbol, value.Value);
     var newPointsValue = DalSpot.Instance.GetPointsValue(order.Symbol, newValue);
     return newPointsValue - pointsValue;
 }
コード例 #32
0
ファイル: BaseRobot.cs プロジェクト: johnmensen/TradeSharp
 /// <summary>
 /// Вызывается на торговых событиях открытие закрытие позиции, срабатывание тейков и стопов
 /// </summary>
 /// <param name="order"></param>
 public virtual void OnTradeEvent(MarketOrder order)
 {
     TerminalLog.Instance.SaveRobotLog(string.Format("робот {0}: срабатывание рыночного ордера {1}, {2}, состояние {3}, side = {4}",
         TypeName, order.ID, order.Symbol, order.State, order.Side));
 }
コード例 #33
0
        private void MakeOrder(string expertComment, string comment, int dealSign, 
            QuoteData curQuote, List<string> hints)
        {
            var tradeVolume = GetEnterVolume();
            if (tradeVolume == 0)
            {
                hints.Add(comment + ", объем входа 0");
                return;
            }

            var order = new MarketOrder
                {
                    ExpertComment = expertComment, // описание проекции
                    Comment = comment,
                    Symbol = ticker,
                    Volume = tradeVolume,
                    Side = dealSign,
                    //StopLoss =
                };

            // запрос входа на сервере
            var status = NewOrder(order, OrderType.Market,
                                  (decimal) (dealSign > 0 ? curQuote.ask : curQuote.bid), 0);
            if (status != RequestStatus.OK)
                hints.Add(comment + ", вход неуспешен: " + status);
        }
コード例 #34
0
ファイル: ChartForm.cs プロジェクト: johnmensen/TradeSharp
        private void UpdateOrdersList(MarketOrder[] posList)
        {
            if (!startupFinished) return;
            if (!updateCompleted.WaitOne()) return; //UpdateQuoteTimeout)) return;
            updateCompleted.Reset();
            try
            {
                // график обрабатывает список позиций и перерисовывается
                var flagRedrawOrders = false;
                if (posList != null)
                    flagRedrawOrders = chart.ProcessOrders(posList);

                if (flagRedrawOrders) // перерисовать
                    chart.RedrawChartSafe();
            }
            finally
            {
                updateCompleted.Set();
            }
        }
コード例 #35
0
ファイル: ChartForm.cs プロジェクト: johnmensen/TradeSharp
        /// <summary>
        /// асинхронно обновить открытые позиции
        /// </summary>        
        public void UpdateOrdersListAsynch(MarketOrder[] posList)
        {
            if (!updateCompleted.WaitOne(WaitFormUpdateInterval)) return;

            var del = new UpdateOrdersListDel(UpdateOrdersList);
            try
            {
                Invoke(del, (object)posList);
            }
            catch (InvalidOperationException) { }
        }
コード例 #36
0
        private List<MarketOrder> MakeMarketOrders(CandleChartControl chart, int accountId, Random rand, int numStepsMax)
        {
            var positions = new List<MarketOrder>();

            foreach (var mark in chart.seriesAsteriks.data)
            {
                var side = mark.Shape == AsteriskTooltip.ShapeType.СтрелкаВниз
                               ? -1
                               : mark.Shape == AsteriskTooltip.ShapeType.СтрелкаВверх ? 1 : 0;
                if (side == 0) continue;
                var pos = new MarketOrder
                              {
                                  AccountID = accountId,
                                  Side = side,
                                  TimeEnter = mark.DateStart.Value,
                                  State = PositionState.Opened,
                                  PriceEnter = mark.Price,
                                  Symbol = chart.Symbol,
                                  Volume = VolumeMin
                              };
                // посчитать объем
                if (numStepsMax > 0)
                    pos.Volume += rand.Next(numStepsMax + 1)*VolumeStep;
                positions.Add(pos);
            }
            return positions;
        }
コード例 #37
0
        /// <summary>
        /// преобразовать запрос на вход / выход из рынка в отложенный ордер
        /// </summary>
        private bool MakeMarketRequest(Account account, string symbol, int?magic,
                                       int volume, int side,
                                       OrderType orderPricing,
                                       decimal requestedPrice, decimal slippagePoints,
                                       string description,
                                       int?closingPositionId, string comment, string expertComment, float?trailingLevel, float?trailingGoal,
                                       out RequestStatus error,
                                       out TradeSharp.ProviderProxyContract.Entity.MarketOrder req)
        {
            Logger.InfoFormat("Dealer [{0}, account: {1}]: MakeMarketRequest({2} {3})",
                              DealerCode, account.ID, side > 0 ? "BUY" : "SELL", symbol);
            error = RequestStatus.OK;
            req   = new TradeSharp.ProviderProxyContract.Entity.MarketOrder(new BrokerOrder());

            if (orderPricing == OrderType.Instant && slippagePoints != 0)
            {
                var slipAbs = DalSpot.Instance.GetAbsValue(symbol, slippagePoints);
                if (slipAbs == 0)
                {
                    Logger.ErrorFormat("Ошибка в FixDealer - нет информации по символу {0} (пересчет проскальзывания)", symbol);
                    errorStorage.AddMessage(new ErrorMessage(DateTime.Now, ErrorMessageType.ОшибкаОтправки,
                                                             string.Format("Ошибка в FixDealer - нет информации по символу {0} (пересчет проскальзывания)", symbol),
                                                             null));
                    error = RequestStatus.ServerError;
                    return(false);
                }
                req.brokerOrder.Slippage = slipAbs;
            }
            int posId = 0;

            if (closingPositionId == null || closingPositionId == 0)
            {
                var order = new MarketOrder
                {
                    AccountID     = account.ID,
                    Side          = side,
                    ID            = 0,
                    Volume        = volume,
                    Symbol        = symbol,
                    Comment       = comment,
                    ExpertComment = expertComment,
                    Magic         = magic,
                    TimeEnter     = DateTime.Now,
                    TrailLevel1   = trailingLevel,
                    TrailTarget1  = trailingGoal,
                    PriceEnter    = (float)requestedPrice,
                    State         = PositionState.StartOpened,
                };

                // создание позы - обработано
                ServerInterface.SaveOrderAndNotifyClient(order, out posId);
                if (posId <= 0)
                {
                    Logger.ErrorFormat("Ошибка в FixDealer - ошибка создания открытой позиции в БД по {0}", symbol);
                    errorStorage.AddMessage(new ErrorMessage(DateTime.Now, ErrorMessageType.ОшибкаОтправки,
                                                             string.Format(
                                                                 "Ошибка в FixDealer - ошибка создания открытой позиции в БД по {0}",
                                                                 symbol),
                                                             null));
                    error = RequestStatus.ServerError;
                    return(false);
                }
            }
            else
            {// закрытие позы
                MarketOrder order;
                ServerInterface.GetMarketOrder(closingPositionId.Value, out order);
                if (order == null)
                {
                    error = RequestStatus.ServerError;
                    Logger.ErrorFormat("FixDealer - MakeMarketRequest - order {0} not found", closingPositionId.Value);
                    return(false);
                }
                order.State = PositionState.StartClosed;
                if (!ServerInterface.ModifyMarketOrder(order))
                {
                    error = RequestStatus.ServerError;
                    Logger.ErrorFormat("FixDealer - MakeMarketRequest - cannot modify order {0}", closingPositionId.Value);
                    return(false);
                }
            }

            req.AccountGroupCode         = account.Group;
            req.brokerOrder.Instrument   = Instrument.Spot;
            req.brokerOrder.OrderPricing = orderPricing == OrderType.Instant ? OrderPricing.Instant : OrderPricing.Market;
            if (req.brokerOrder.OrderPricing == OrderPricing.Instant)
            {
                req.brokerOrder.RequestedPrice = requestedPrice == 0 ? (decimal?)null : requestedPrice;
            }
            req.brokerOrder.Side              = side;
            req.brokerOrder.Volume            = volume;
            req.brokerOrder.Ticker            = symbol;
            req.brokerOrder.RequestId         = posId != 0 ? posId : (int)RequestUniqueId;
            req.brokerOrder.DealerCode        = DealerCode;
            req.brokerOrder.TimeCreated       = DateTime.Now;
            req.brokerOrder.ClosingPositionID = closingPositionId;
            req.brokerOrder.AccountID         = account.ID;
            req.brokerOrder.Magic             = magic;
            req.brokerOrder.Comment           = comment;
            req.brokerOrder.ExpertComment     = expertComment;

            requestWatchdog.AddRequest(new RequestWatchdogItem
            {
                requestId     = req.brokerOrder.RequestId, requestTime = DateTime.Now,
                requestSymbol = symbol, requestType = (DealType)side
            });

            // сохранить сообщение в БД
            try
            {
                ServerInterface.SaveProviderMessage(req.brokerOrder);
            }
            catch (Exception ex)
            {
                error = RequestStatus.SerializationError;
                Logger.ErrorFormat("Дилер {0}: ошибка сохранения запроса брокеру: {1}",
                                   DealerCode, ex);
                errorStorage.AddMessage(new ErrorMessage(DateTime.Now, ErrorMessageType.ОшибкаОтправки,
                                                         string.Format("Дилер {0}: ошибка сохранения запроса брокеру", DealerCode), ex));
                return(false);
            }

            return(true);
        }