/// <summary>
        /// Initializes a new instance of the <see cref="ProductInfo"/> class.
        /// </summary>
        /// <param name="orderedProduct">The ordered product.</param>
        /// <param name="order">The order.</param>
        public ProductInfo(OrderedProduct orderedProduct, IOrderInfo order) : this()
        {
            Order = order;

            Id = orderedProduct.ProductId;

            Title     = orderedProduct.Title;
            SKU       = orderedProduct.SKU;
            Weight    = orderedProduct.Weight;
            Length    = orderedProduct.Length;
            Width     = orderedProduct.Width;
            Height    = orderedProduct.Height;
            Vat       = orderedProduct.Vat;
            ItemCount = orderedProduct.ItemCount.GetValueOrDefault(1);

            ChangedOn = orderedProduct.UpdateDate;

            RangesString = orderedProduct.RangesString;

            OriginalPriceInCents = orderedProduct.PriceInCents;

            DiscountAmountInCents     = orderedProduct.OrderedProductDiscountAmount;
            DiscountPercentage        = orderedProduct.OrderedProductDiscountPercentage;
            DiscountExcludingVariants = orderedProduct.OrderedProductDiscountExcludingVariants;

            DocTypeAlias = orderedProduct.TypeAlias ?? orderedProduct.DoctypeAlias;
        }
Beispiel #2
0
        /// <summary>
        /// Loads current Copier account orders at creation.
        /// </summary>
        public override void Init()
        {
            int ordersTotal = OrdersTotal();

            for (int i = 0; i < ordersTotal; i++)
            {
                IOrderInfo order = OrderGet(i, SelectionType.SELECT_BY_POS, SelectionPool.MODE_TRADES);
                if (order != null)
                {
                    /*
                     * if (order.GetMagic() != 0)
                     * {
                     *  Console.WriteLine("Closing order: " + order);
                     *  CloseOrder(order);
                     * }
                     * continue;
                     */
                    if (order.GetMagic() != 0)
                    {
                        _ordersMap.Add(
                            order.GetMagic(), // Master's order ticket
                            order.GetTicket()
                            );
                        Info(String.Format("Master order {0} is mapped to {1}", order.GetMagic(), order));
                    }
                    else
                    {
                        Info(String.Format("Custom order {0} left unmanaged", order));

                        //lets try to close this
                        Info(String.Format("Closing orphaned order: {0}", order));
                    }
                }
            }
        }
Beispiel #3
0
        private bool AddToChart(string userId, string locationid, IOrderInfo orderInfo)
        {
            var location = _locationsService.FirstOrDefault(p => p.Id == locationid);

            if (location == null)
            {
                return(false);
            }

            try
            {
                _carts.AddOrUpdate(userId, user =>
                {
                    var orderDetailModels = CreateOrderDetailModels(user, location, orderInfo);
                    return(new List <OrderDetail>()
                    {
                        orderDetailModels
                    });
                }, (user, orderDetails) =>
                {
                    orderDetails.Add(CreateOrderDetailModels(user, location, orderInfo));
                    return(orderDetails);
                });
            }
            catch (Exception e)
            {
                return(false);
            }

            return(true);
        }
Beispiel #4
0
 public OComparator(IOrderInfo o)
 {
     _closeTime = o.GetCloseTime();
     _symbol    = o.GetSymbol();
     _tradeOp   = o.GetTradeOperation();
     _price     = o.GetOpenPrice();
     _time      = o.GetOpenTime();
     _magic     = o.GetMagic();
 }
Beispiel #5
0
        public IOrderInfo Merge(IOrderInfo orderInfo)
        {
            var from = ((OrderImpl)orderInfo);

            _diffBitMap = from._diffBitMap;
            if (IsTradeOperationChanged())
            {
                Type = from.Type;
            }
            if (IsOpenTimeChanged())
            {
                OpenTime = from.OpenTime;
            }
            if (IsCloseTimeChanged())
            {
                CloseTime = from.CloseTime;
                Comment   = from.Comment;
            }
            if (IsExpirationTimeChanged())
            {
                Expiration = from.Expiration;
            }
            if (IsLotsChanged())
            {
                Lots = from.Lots;
            }
            if (IsOpenPriceChanged())
            {
                OpenPrice = from.OpenPrice;
            }
            if (IsClosePriceChanged())
            {
                ClosePrice = from.ClosePrice;
            }
            if (IsStopLossChanged())
            {
                Sl = from.Sl;
            }
            if (IsTakeProfitChanged())
            {
                Tp = from.Tp;
            }
            if (IsProfitChanged())
            {
                Profit = from.Profit;
            }
            if (IsCommissionChanged())
            {
                Commission = from.Commission;
            }
            if (IsSwapChanged())
            {
                Swap = from.Swap;
            }
            _str = null;
            return(this);
        }
Beispiel #6
0
        public void SetClosedHedgeOf(IOrderInfo order)
        {
            _closedHedgeOf = order.Ticket();
            var orderImpl = order as OrderImpl;

            Debug.Assert(orderImpl != null, "orderImpl != null");
            orderImpl._closedBy = Ticket();
            _str = null;
        }
Beispiel #7
0
 public bool IsSameLiveOrder(IOrderInfo o)
 {
     return(_symbol == o.GetSymbol() &&
            _tradeOp == o.GetTradeOperation() &&
            _price == o.GetOpenPrice() &&
            _time == o.GetOpenTime() &&
            _magic == o.GetMagic()
            );
 }
Beispiel #8
0
 internal void AddClosedOrDeletedOrder(IOrderInfo o)
 {
     if (isClosed(o))
     {
         ClosedOrders.Add(o);
     }
     else
     {
         DeletedOrders.Add(o);
     }
 }
Beispiel #9
0
        public void SetNext(IOrderInfo nextP)
        {
            _next = nextP.Ticket();
            nextP.SetWasEverLiveOrder(_wasLiveOrder);
            //
            var orderImpl = nextP as OrderImpl;

            Debug.Assert(orderImpl != null, "orderImpl != null");
            orderImpl._prev = Ticket();
            _str            = null;
        }
Beispiel #10
0
        public void SetPrev(IOrderInfo prev)
        {
            _prev         = prev.Ticket();
            _wasLiveOrder = prev.WasEverLiveOrder();
            //
            var orderImpl = prev as OrderImpl;

            Debug.Assert(orderImpl != null, "orderImpl != null");
            orderImpl._next = Ticket();
            _str            = null;
        }
Beispiel #11
0
            private long NextTicketFromComment(IOrderInfo o)
            {
                var  toComment = @"to #";
                long t;

                if (o.GetComment().StartsWith(toComment) &&
                    long.TryParse(o.GetComment().Substring(toComment.Length), out t))
                {
                    return(t);
                }
                return(0);
            }
Beispiel #12
0
        private bool CloseOrder(IOrderInfo order)
        {
            try
            {
                TradeOperation orderType = order.GetTradeOperation();

                Console.WriteLine("Closing an order - order.closePrice: {0} market.bid: {1} market.ask: {2} order.OrderType: {3}", order.GetClosePrice(), Marketinfo(order.GetSymbol(), MarketInfo.MODE_BID), Marketinfo(order.GetSymbol(), MarketInfo.MODE_ASK), orderType);

                switch (orderType)
                {
                case TradeOperation.OP_BUY:
                case TradeOperation.OP_SELL:
                    RefreshRates();
                    if (order.GetTicket() > 0 && OrderClose(order.GetTicket(), order.GetLots(),
                                                            Marketinfo(order.GetSymbol(),
                                                                       orderType == TradeOperation.OP_BUY
                                                      ? MarketInfo.MODE_BID
                                                      : MarketInfo.MODE_ASK),
                                                            20, 0))
                    {
                        Info(String.Format("Order {0} has been closed", order));
                        return(true);
                    }
                    Info(String.Format("Order {0} to be closed; todo", order));
                    return(false);

                default:
                    if (OrderDelete(order.GetTicket(), Color.Black))
                    {
                        Info(String.Format("Order {0} has been deleted", order));
                        return(true);
                    }
                    else
                    {
                        Info(String.Format("Can not delete order {0}", order));
                        return(false);
                    }
                }
            }
            catch (ErrInvalidTicket)
            {
                Info(String.Format("Looks like order {0} has been deleted manually", order));
                return(true);
            }
            catch (ErrInvalidPrice)
            {
                Info(String.Format("## ErrInvalidPrice - Price slippage ## - order.closePrice: {0} market.bid: {1} market.ask: {2} order.OrderType: {3}", order.GetClosePrice(), Marketinfo(order.GetSymbol(), MarketInfo.MODE_BID), Marketinfo(order.GetSymbol(), MarketInfo.MODE_ASK), order.GetTradeOperation()));
                return(false);
            }
        }
Beispiel #13
0
            private double Lots(IOrderInfo order)
            {
                double lots = 0;

                if (order.GetLots() == 0)
                {
                    IOrderInfo cb;
                    if (_orders.TryGetValue(order.GetClosedHedgeOf(), out cb))
                    {
                        lots = cb.GetLots();
                    }
                }
                else
                {
                    lots = order.GetLots();
                }
                return(lots);
            }
 public void BindUI_fetches_orders_from_business_layer_and_binds_them_to_view()
 {
     //arrange
     var orders = new IOrderInfo[] { };
     var orderFactory = MockRepository.GenerateMock<IOrderFactory>();
     var view = MockRepository.GenerateMock<IOrderListView>();
     var presenter = MockRepository.GenerateMock<IOrderListPresenter>();
     var target = new OrderListDataBinder(orderFactory);
     orderFactory.Expect(x => x.FetchInfoList())
         .Return(orders);
     presenter.Expect(x => x.View)
         .Return(view);
     view.Expect(x => x.SetOrdersBindingSourceDataSource(orders));
     //act
     target.BindUI(presenter);
     //assert
     orderFactory.VerifyAllExpectations();
     view.VerifyAllExpectations();
 }
        public void BindUI_fetches_orders_from_business_layer_and_binds_them_to_view()
        {
            //arrange
            var orders       = new IOrderInfo[] { };
            var orderFactory = MockRepository.GenerateMock <IOrderFactory>();
            var view         = MockRepository.GenerateMock <IOrderListView>();
            var presenter    = MockRepository.GenerateMock <IOrderListPresenter>();
            var target       = new OrderListDataBinder(orderFactory);

            orderFactory.Expect(x => x.FetchInfoList())
            .Return(orders);
            presenter.Expect(x => x.View)
            .Return(view);
            view.Expect(x => x.SetOrdersBindingSourceDataSource(orders));
            //act
            target.BindUI(presenter);
            //assert
            orderFactory.VerifyAllExpectations();
            view.VerifyAllExpectations();
        }
Beispiel #16
0
 internal void MasterOrderClosedOrDeleted(IOrderInfo masterOrder)
 {
     if (_ordersMap.Contains(masterOrder.GetTicket()))
     {
         var        orderTicket = (int)_ordersMap[masterOrder.GetTicket()];
         IOrderInfo order       = OrderGet(orderTicket, SelectionType.SELECT_BY_TICKET, SelectionPool.MODE_TRADES);
         if (order != null)
         {
             if (CloseOrder(order))
             {
                 _ordersMap.Remove(masterOrder.GetTicket());
             }
         }
         else
         {
             Info(String.Format("Order {0} not found", orderTicket));
             _ordersMap.Remove(masterOrder.GetTicket());
         }
     }
 }
		public static ProductInfo CreateProductInfo(int productPriceInCents, int itemCount, decimal vat = 19, DiscountProduct discount = null, IOrderInfo order = null)
		{
			var productInfo = new ProductInfo();
			productInfo.IsDiscounted = discount == null;
			productInfo.OriginalPriceInCents = productPriceInCents;
			productInfo.Ranges = new List<Range>();
			productInfo.Vat = vat;
			productInfo.ItemCount = itemCount;
			productInfo.Tags = new string[0];
			if (order != null)
			{
				order.OrderLines = new List<OrderLine> {new OrderLine(productInfo, order)};
			}
			productInfo.Order = order ?? CreateOrderInfo(productInfo);
			if (discount != null)
			{
				SetProductDiscountOnProductInfo(productInfo, discount);
			}
			return productInfo;
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="ProductInfo"/> class.
        /// </summary>
        /// <param name="product">The product.</param>
        /// <param name="order">The order.</param>
        /// <param name="itemCount">The item count.</param>
        public ProductInfo(Product product, OrderInfo order, int itemCount) : this()
        {
            if (product == null)
            {
                return;
                //throw new ArgumentNullException("product null");
            }
            Order    = order;
            _product = product;

            Id        = product.Id;
            ItemCount = itemCount;
            Title     = product.Title;
            SKU       = product.SKU;
            Tags      = product.Tags;
            Weight    = product.Weight;
            Length    = product.Length;
            Width     = product.Width;
            Height    = product.Height;
            Vat       = product.Vat;
            ChangedOn = DateTime.Now;

            Ranges = product.Ranges.ToList();             // = localized

            OriginalPriceInCents = product.Price.BeforeDiscount.ValueInCents();

            var discount = IO.Container.Resolve <IProductDiscountService>().GetDiscountByProductId(product.Id, order.Localization, order);

            if (discount != null)
            {
                DiscountId = discount.Id;
            }
            IO.Container.Resolve <IOrderUpdatingService>().UpdateProductInfoDiscountInformation(this);

            DocTypeAlias = product.NodeTypeAlias;
        }
Beispiel #19
0
        private bool AddToChart(string userId, string locationid, IOrderInfo orderInfo)
        {
            var location = _locationsService.FirstOrDefault(p => p.Id == locationid);
            if (location == null) return false;

            try
            {
                _carts.AddOrUpdate(userId, user =>
                    {
                        var orderDetailModels = CreateOrderDetailModels(user, location, orderInfo);
                        return new List<OrderDetail>() { orderDetailModels };
                    }, (user, orderDetails) =>
                        {
                            orderDetails.Add(CreateOrderDetailModels(user, location, orderInfo));
                            return orderDetails;
                        });
            }
            catch (Exception e)
            {
                return false;

            }

            return true;
        }
        public static void NewTerminal(object account)
        {
            MTAccount MetaAccount = (MTAccount)account;

            try
            {
                NJ4XServer server = MainController.m_listNJ4XServer.Find(x => x.id == MetaAccount.server_id);

                //---- NJ4X LOG -----
                string strLog = "The OutControl Server (" + server.name + ") Is Executing New Terminal.";
                Socket_Manager.Instance.SendNj4xServerLog(server.id, DateTime.Now, strLog);

                string AproveState     = MetaAccount.status;
                string AccountID       = MetaAccount.id;
                string ServerHost      = server.server_ip;
                int    ServerPort      = server.server_port;
                string BrokerAddress   = MetaAccount.broker.server_ip;
                string AccountNumber   = MetaAccount.account_number;
                string AccountPassword = MetaAccount.account_password;
                bool   IsMT5           = (MetaAccount.platform == "MT5");

                int magic   = 199589;
                int slipage = 50;

                double   min_lot             = MetaAccount.plan.min_lot;
                double   max_lot             = MetaAccount.plan.max_lot;
                double   max_daily_profit    = MetaAccount.plan.max_daily_profit;
                double   max_daily_loss      = MetaAccount.plan.max_daily_loss;
                bool     daily_loss_fix_flag = MetaAccount.plan.daily_loss_fix;
                double   max_total_profit    = MetaAccount.plan.max_total_profit;
                double   max_total_loss      = MetaAccount.plan.max_total_loss;
                bool     total_loss_fix_flag = MetaAccount.plan.total_loss_fix;
                int      max_orders          = MetaAccount.plan.max_orders;
                string[] currency_pair       = MetaAccount.plan.currency_pair;

                bool FLAG_MAX_DAILY_PROFIT = false;
                bool FLAG_MAX_DAILY_LOSS   = false;
                bool FLAG_MAX_TOTAL_PROFIT = false;
                bool FLAG_MAX_TOTAL_LOSS   = false;

                var mt4 = new nj4x.Strategy()
                {
                    IsReconnect = false
                };
                Console.WriteLine(String.Format("*** Connecting, {0}***", AccountNumber));
                mt4.SetPositionListener(
                    delegate(IPositionInfo initialPositionInfo)
                {
                    Console.WriteLine("initialPositionInfo=" + initialPositionInfo);
                    CoordinationDoneEvent.Set();
                },
                    delegate(IPositionInfo info, IPositionChangeInfo changes)
                {
                    //---------------------- INFO LOG ----------------------
                    foreach (IOrderInfo o in changes.GetNewOrders())
                    {
                        Console.WriteLine("NEW: " + o);
                        Socket_Manager.Instance.SendAccountLog(AccountID, DateTime.Now, "NEW: " + o);
                        if (AproveState != "Aprove")
                        {
                            Console.WriteLine("SORRY, YOUR ACCOUNT IS NOT APROVED! " + mt4.AccountName());
                            Socket_Manager.Instance.SendAccountLog(AccountID, DateTime.Now,
                                                                   "SORRY, YOUR ACCOUNT IS NOT APROVED! " + mt4.AccountName());
                            mt4.OrderCloseAll();
                            return(Task.FromResult(0));
                        }
                        //----------------------------- Check Symbols ------------------------------
                        bool allowed = false;
                        foreach (string strSymbol in currency_pair)
                        {
                            if (strSymbol == o.GetSymbol())
                            {
                                allowed = true;
                            }
                        }

                        if (allowed == false)
                        {
                            Console.WriteLine("SORRY, THIS SYMBOL IS NOT ALLOWED! " + mt4.AccountName());
                            Socket_Manager.Instance.SendAccountLog(AccountID, DateTime.Now,
                                                                   "SORRY, THIS SYMBOL IS NOT ALLOWED! " + mt4.AccountName());

                            mt4.OrderClose(o.GetTicket(), o.GetLots(), o.GetOpenPrice(), slipage, 0);
                            return(Task.FromResult(0));
                        }

                        //--------------------------------- Check Lots ------------------------------
                        if (o.GetLots() < min_lot || o.GetLots() > max_lot)
                        {
                            Console.WriteLine("SORRY, YOU VOLUMN IS OUT OF RANGE! " + mt4.AccountName());
                            Socket_Manager.Instance.SendAccountLog(AccountID, DateTime.Now,
                                                                   "SORRY, YOU VOLUMN IS OUT OF RANGE! " + mt4.AccountName());

                            mt4.OrderClose(o.GetTicket(), o.GetLots(), o.GetOpenPrice(), slipage, 0);
                            return(Task.FromResult(0));
                        }

                        double DailyLots = 0;
                        for (int v = 0; v < mt4.OrdersTotal(); ++v)
                        {
                            IOrderInfo orderInfo = mt4.OrderGet(v, SelectionType.SELECT_BY_POS, SelectionPool.MODE_TRADES);
                            if (orderInfo != null)
                            {
                                DailyLots += orderInfo.GetLots();
                            }
                        }

                        if (o.GetLots() < min_lot || o.GetLots() > max_lot)
                        {
                            Console.WriteLine("SORRY, YOU LOTS IS OUT OF MAX DAILY LOTS RANGE! " + mt4.AccountName());
                            Socket_Manager.Instance.SendAccountLog(AccountID, DateTime.Now,
                                                                   "SORRY, YOU LOTS IS OUT OF MAX DAILY LOTS RANGE! " + mt4.AccountName());

                            mt4.OrderClose(o.GetTicket(), o.GetLots(), o.GetOpenPrice(), slipage, 0);
                            return(Task.FromResult(0));
                        }
                    }
                    foreach (IOrderInfo o in changes.GetModifiedOrders())
                    {
                        Console.WriteLine("MODIFIED: " + o);
                        Socket_Manager.Instance.SendAccountLog(AccountID, DateTime.Now,
                                                               "MODIFIED: " + o);
                        if (AproveState != "Aprove")
                        {
                            Console.WriteLine("SORRY, YOUR ACCOUNT IS NOT APROVED! " + mt4.AccountName());
                            Socket_Manager.Instance.SendAccountLog(AccountID, DateTime.Now,
                                                                   "SORRY, YOUR ACCOUNT IS NOT APROVED! " + mt4.AccountName());
                            mt4.OrderCloseAll();
                            return(Task.FromResult(0));
                        }
                        //--------------------------------- Check Lots ------------------------------
                        if (o.GetLots() < min_lot || o.GetLots() > max_lot)
                        {
                            Console.WriteLine("SORRY, YOU VOLUMN IS OUT OF RANGE! " + mt4.AccountName());
                            Socket_Manager.Instance.SendAccountLog(AccountID, DateTime.Now,
                                                                   "SORRY, YOU VOLUMN IS OUT OF RANGE! " + mt4.AccountName());

                            mt4.OrderClose(o.GetTicket(), o.GetLots(), o.GetOpenPrice(), slipage, 0);
                            return(Task.FromResult(0));
                        }

                        double DailyLots = 0;
                        for (int v = 0; v < mt4.OrdersTotal(); ++v)
                        {
                            IOrderInfo orderInfo = mt4.OrderGet(v, SelectionType.SELECT_BY_POS, SelectionPool.MODE_TRADES);
                            if (orderInfo != null)
                            {
                                DailyLots += orderInfo.GetLots();
                            }
                        }

                        if (o.GetLots() < min_lot || o.GetLots() > max_lot)
                        {
                            Console.WriteLine("SORRY, YOU LOTS IS OUT OF MAX DAILY LOTS RANGE! " + mt4.AccountName());
                            Socket_Manager.Instance.SendAccountLog(AccountID, DateTime.Now,
                                                                   "SORRY, YOU LOTS IS OUT OF MAX DAILY LOTS RANGE! " + mt4.AccountName());

                            mt4.OrderClose(o.GetTicket(), o.GetLots(), o.GetOpenPrice(), slipage, 0);
                            return(Task.FromResult(0));
                        }
                    }
                    foreach (IOrderInfo o in changes.GetClosedOrders())
                    {
                        Console.WriteLine("CLOSED: " + o);
                        Socket_Manager.Instance.SendAccountLog(AccountID, DateTime.Now,
                                                               "CLOSED: " + o);
                    }
                    foreach (IOrderInfo o in changes.GetDeletedOrders())
                    {
                        Console.WriteLine("DELETED: " + o);
                        Socket_Manager.Instance.SendAccountLog(AccountID, DateTime.Now,
                                                               "DELETED: " + o);
                    }

                    if (AproveState != "Aprove")
                    {
                        Console.WriteLine("SORRY, YOUR ACCOUNT IS NOT APROVED! " + mt4.AccountName());
                        Socket_Manager.Instance.SendAccountLog(AccountID, DateTime.Now,
                                                               "SORRY, YOUR ACCOUNT IS NOT APROVED! " + mt4.AccountName());
                        mt4.OrderCloseAll();
                        return(Task.FromResult(0));
                    }

                    //------------------------------- Calculate Profit Information ----------------------------
                    double TotalMaxBalance = 0;
                    double DailyMaxBalance = 0;
                    double TotalProfit     = 0;
                    double DailyProfit     = 0;

                    double CurBalance = mt4.AccountBalance();
                    TotalMaxBalance   = CurBalance;
                    DailyMaxBalance   = CurBalance;

                    int total = mt4.OrdersHistoryTotal();
                    for (int v = 0; v < total; ++v)
                    {
                        IOrderInfo orderInfo = mt4.OrderGet(v, SelectionType.SELECT_BY_POS, SelectionPool.MODE_HISTORY);
                        if (orderInfo != null)
                        {
                            if (orderInfo.GetTradeOperation() == TradeOperation.OP_BUY || orderInfo.GetTradeOperation() == TradeOperation.OP_SELL)
                            {
                                if (CurBalance > TotalMaxBalance || TotalMaxBalance == 0)
                                {
                                    TotalMaxBalance = CurBalance;
                                }
                                CurBalance   = CurBalance - orderInfo.GetProfit();
                                TotalProfit += orderInfo.GetProfit();

                                if (orderInfo.GetCloseTime() >= mt4.iTime(orderInfo.GetSymbol(), Timeframe.PERIOD_D1, 0))
                                {
                                    if (CurBalance > DailyMaxBalance || DailyMaxBalance == 0)
                                    {
                                        DailyMaxBalance = CurBalance;
                                    }
                                    DailyProfit += orderInfo.GetProfit();
                                }
                            }
                        }
                    }

                    Console.WriteLine("TotalMaxBalance: " + TotalMaxBalance.ToString());
                    Console.WriteLine("DailyMaxBalance: " + DailyMaxBalance.ToString());
                    Console.WriteLine("TotalProfit: " + TotalProfit.ToString());
                    Console.WriteLine("DailyProfit: " + DailyProfit.ToString());
                    if (DailyProfit >= max_daily_profit)
                    {
                        mt4.OrderCloseAll();
                        Console.WriteLine("CONGRATS, YOU REACHED THE MAX PROFIT TODAY! " + mt4.AccountName());
                        Socket_Manager.Instance.SendAccountLog(AccountID, DateTime.Now,
                                                               "CONGRATS, YOU REACHED THE MAX PROFIT TODAY! " + mt4.AccountName());

                        FLAG_MAX_DAILY_PROFIT = true;
                        return(Task.FromResult(0));
                    }
                    else
                    {
                        FLAG_MAX_DAILY_PROFIT = false;
                    }



                    //CheckTotalProfit
                    if (TotalProfit >= max_total_profit)
                    {
                        mt4.OrderCloseAll();
                        Console.WriteLine("CONGRATS, YOU REACHED THE MAX TOTAL PROFIT! " + mt4.AccountName());
                        Socket_Manager.Instance.SendAccountLog(AccountID, DateTime.Now,
                                                               "CONGRATS, YOU REACHED THE MAX TOTAL PROFIT! " + mt4.AccountName());

                        FLAG_MAX_TOTAL_PROFIT = true;
                        return(Task.FromResult(0));
                    }
                    else
                    {
                        FLAG_MAX_TOTAL_PROFIT = false;
                    }


                    //Check Fix Flag
                    CurBalance = mt4.AccountBalance();
                    if (daily_loss_fix_flag == false)
                    {
                        DailyProfit = CurBalance - DailyMaxBalance;
                    }
                    if (total_loss_fix_flag == false)
                    {
                        TotalProfit = CurBalance - TotalMaxBalance;
                    }


                    if (DailyProfit <= max_daily_loss)
                    {
                        mt4.OrderCloseAll();
                        Console.WriteLine("SORRY, YOU REACHED THE MAX LOSS TODAY! " + mt4.AccountName());
                        Socket_Manager.Instance.SendAccountLog(AccountID, DateTime.Now,
                                                               "SORRY, YOU REACHED THE MAX LOSS TODAY! " + mt4.AccountName());

                        FLAG_MAX_DAILY_LOSS = true;
                        return(Task.FromResult(0));
                    }
                    else
                    {
                        FLAG_MAX_DAILY_LOSS = false;
                    }


                    if (TotalProfit <= max_total_loss)
                    {
                        mt4.OrderCloseAll();
                        Console.WriteLine("SORRY, YOU REACHED THE MAX TOTAL LOSS! " + mt4.AccountName());
                        Socket_Manager.Instance.SendAccountLog(AccountID, DateTime.Now,
                                                               "SORRY, YOU REACHED THE MAX TOTAL LOSS! " + mt4.AccountName());

                        FLAG_MAX_TOTAL_LOSS = true;
                        return(Task.FromResult(0));
                    }
                    else
                    {
                        FLAG_MAX_TOTAL_LOSS = false;
                    }


                    return(Task.FromResult(0));
                }
                    );


                mt4.Connect(ServerHost, ServerPort,
                            new Broker(IsMT5 ? $"5*{BrokerAddress}" : BrokerAddress),
                            AccountNumber,
                            AccountPassword);

                _terminals.Add(mt4);

                //---- NJ4X LOG -----
                Console.WriteLine(String.Format("*** Connected, {0}***", mt4.GetVersion()));
                strLog = "The OutControl Server (" + server.name + ") Successed To Add New Terminal.";
                Socket_Manager.Instance.SendNj4xServerLog(server.id, DateTime.Now, strLog);

                using (mt4)
                {
                    int total = mt4.OrdersHistoryTotal();
                    for (int v = 0; v < Math.Min(10, total); ++v)
                    {
                        IOrderInfo orderInfo = mt4.OrderGet(v, SelectionType.SELECT_BY_POS, SelectionPool.MODE_HISTORY);
                        if (orderInfo != null)
                        {
                            Console.WriteLine(
                                String.Format("Historical order #{0}, P/L={1}, type={2}, symbol={3}, comments={4}",
                                              orderInfo.GetTicket(),
                                              orderInfo.GetProfit(),
                                              orderInfo.GetTradeOperation(),
                                              orderInfo.GetSymbol(),
                                              orderInfo.GetComment()
                                              ));
                        }
                    }
                    //
                    total = mt4.OrdersTotal();
                    for (int v = 0; v < Math.Min(10, total); ++v)
                    {
                        IOrderInfo orderInfo = mt4.OrderGet(v, SelectionType.SELECT_BY_POS, SelectionPool.MODE_TRADES);
                        if (orderInfo != null)
                        {
                            Console.WriteLine(
                                String.Format("LIVE order #{0}, P/L={1}, type={2}, symbol={3}, comments={4}",
                                              orderInfo.GetTicket(),
                                              orderInfo.GetProfit(),
                                              orderInfo.GetTradeOperation(),
                                              orderInfo.GetSymbol(),
                                              orderInfo.GetComment()
                                              ));
                        }
                    }
                    while (true)
                    {
                        Thread.Sleep(10);
                    }
                }
            }
            catch
            {
                Console.WriteLine("*** Server is not connected or Your Account is not assigned Server! *** " + MetaAccount.account_number);
            }
        }
Beispiel #21
0
        private OrderDetail CreateOrderDetailModels(string user, LocationModel location, IOrderInfo orderInfo)
        {
            //set user as the id for this order until this order move from cart;
            if (location.IsAvailable && location.InLockState == false)
            {
                if (_locationsService.SetAsTemporaryUnAvailable(location.Id))
                {
                    var orderDetailModels = new OrderDetail { OrderId = user };

                    double totalDays = Math.Abs((orderInfo.Start - orderInfo.End).TotalDays);

                    orderDetailModels.Start = orderInfo.Start;
                    orderDetailModels.End = orderInfo.End;
                    orderDetailModels.LocationId = location.Id;
                    orderDetailModels.Total = totalDays * location.PricePerDay;

                    return orderDetailModels;
                }
            }
            throw new Exception("Could't create order");
        }
Beispiel #22
0
 public Task<bool> AddToCartAsync(string userId, string locationid, IOrderInfo orderInfo)
 {
     return Task.Run(() => AddToChart(userId, locationid, orderInfo));
 }
Beispiel #23
0
 public Order(IOrderInfo info, IApplicationData<IScorpionDataProvider> dataProviderFactory, SynchronizationContext synchronizationContext, ISecurityManager securityManager)
     : base(dataProviderFactory, securityManager)
 {
     this.info = info;
     this.synchronizationContext = synchronizationContext;
 }
Beispiel #24
0
 public Task <bool> AddToCartAsync(string userId, string locationid, IOrderInfo orderInfo)
 {
     return(Task.Run(() => AddToChart(userId, locationid, orderInfo)));
 }
Beispiel #25
0
 private bool isClosed(IOrderInfo o)
 {
     return(o.GetTradeOperation() == TradeOperation.OP_BUY || o.GetTradeOperation() == TradeOperation.OP_SELL);
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="ProductInfo"/> class.
		/// </summary>
		/// <param name="product">The product.</param>
		/// <param name="order">The order.</param>
		/// <param name="itemCount">The item count.</param>
		public ProductInfo(Product product, OrderInfo order, int itemCount) : this()
		{
			if (product == null)
			{
				return;
				//throw new ArgumentNullException("product null");
			}
			Order = order;
			_product = product;

			Id = product.Id;
			ItemCount = itemCount;
			Title = product.Title;
			SKU = product.SKU;
			Tags = product.Tags;
			Weight = product.Weight;
			Length = product.Length;
			Width = product.Width;
			Height = product.Height;
			Vat = product.Vat;
			ChangedOn = DateTime.Now;

			Ranges = product.Ranges.ToList(); // = localized

			OriginalPriceInCents = product.Price.BeforeDiscount.ValueInCents();

			var discount = IO.Container.Resolve<IProductDiscountService>().GetDiscountByProductId(product.Id, order.Localization, order);
			if (discount != null)
			{
				DiscountId = discount.Id;
			}
			IO.Container.Resolve<IOrderUpdatingService>().UpdateProductInfoDiscountInformation(this);

			DocTypeAlias = product.NodeTypeAlias;
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="ProductInfo"/> class.
		/// </summary>
		/// <param name="orderedProduct">The ordered product.</param>
		/// <param name="order">The order.</param>
		public ProductInfo(OrderedProduct orderedProduct, IOrderInfo order) : this()
		{
			Order = order;

			Id = orderedProduct.ProductId;

			Title = orderedProduct.Title;
			SKU = orderedProduct.SKU;
			Weight = orderedProduct.Weight;
			Length = orderedProduct.Length;
			Width = orderedProduct.Width;
			Height = orderedProduct.Height;
			Vat = orderedProduct.Vat;
			ItemCount = orderedProduct.ItemCount.GetValueOrDefault(1);

			ChangedOn = orderedProduct.UpdateDate;

			RangesString = orderedProduct.RangesString;

			OriginalPriceInCents = orderedProduct.PriceInCents;

			DiscountAmountInCents = orderedProduct.OrderedProductDiscountAmount;
			DiscountPercentage = orderedProduct.OrderedProductDiscountPercentage;
			DiscountExcludingVariants = orderedProduct.OrderedProductDiscountExcludingVariants;

			DocTypeAlias = orderedProduct.TypeAlias ?? orderedProduct.DoctypeAlias;
		}
Beispiel #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OrderLine"/> class.
 /// </summary>
 /// <param name="productInfo">The product information.</param>
 /// <param name="order">The order.</param>
 public OrderLine(ProductInfo productInfo, IOrderInfo order)
 {
     Order             = order;
     productInfo.Order = order;
     ProductInfo       = productInfo;
 }
Beispiel #29
0
        private OrderDetail CreateOrderDetailModels(string user, LocationModel location, IOrderInfo orderInfo)
        {
            //set user as the id for this order until this order move from cart;
            if (location.IsAvailable && location.InLockState == false)
            {
                if (_locationsService.SetAsTemporaryUnAvailable(location.Id))
                {
                    var orderDetailModels = new OrderDetail {
                        OrderId = user
                    };

                    double totalDays = Math.Abs((orderInfo.Start - orderInfo.End).TotalDays);

                    orderDetailModels.Start      = orderInfo.Start;
                    orderDetailModels.End        = orderInfo.End;
                    orderDetailModels.LocationId = location.Id;
                    orderDetailModels.Total      = totalDays * location.PricePerDay;

                    return(orderDetailModels);
                }
            }
            throw new Exception("Could't create order");
        }
Beispiel #30
0
        static void Main(string[] args)
        {
            // Create strategy
            var mt4 = new Strategy();

            // Connect to the Terminal Server
            mt4.Connect(
                ConfigurationManager.AppSettings["terminal_host"],
                int.Parse(ConfigurationManager.AppSettings["terminal_port"]),
                new Broker(ConfigurationManager.AppSettings["broker"]),
                ConfigurationManager.AppSettings["account"],
                ConfigurationManager.AppSettings["password"]
                );
            // Use API methods …

            Console.WriteLine($"Account {mt4.AccountNumber()}");
            Console.WriteLine($"Equity {mt4.AccountEquity()}");
            Thread.Sleep(3000);
            Console.Clear();
            var Total     = mt4.OrdersTotal();
            var Total_tmp = Total;
            //IOrderInfo Order_info = mt4.OrderGet(15328321, SelectionType.SELECT_BY_TICKET, SelectionPool.MODE_TRADES);
            IOrderInfo Order_info = mt4.OrderGet(6, SelectionType.SELECT_BY_POS, SelectionPool.MODE_TRADES);
            var        open_Price = Order_info.GetOpenPrice();

            Console.WriteLine($"Ticket ID :{Order_info.GetTicket()} . Open Price :{open_Price}");
            //while (true)
            //{
            //    //Console.WriteLine($"{Total}");
            //    if()
            //}

            //while (true)
            //{
            //    double bid = mt4.Marketinfo("AUDCAD-STD", MarketInfo.MODE_BID);
            //    Console.WriteLine($"AUDCAD-STD bid={bid}");
            //    Thread.Sleep(50);
            //    Console.Clear();
            //}
            //double bid = mt4.Marketinfo("AUDCAD-STD", MarketInfo.MODE_BID);
            //try
            //{
            //    var ticket = mt4.OrderSend("AUDCAD-STD",
            //        TradeOperation.OP_SELL,
            //        0.01, bid, 2, 0, 0,
            //        "Order_Sell_Demo", 0,
            //        MT4.NoExpiration
            //        );
            //    Console.WriteLine($"New Sell_Order ID: {ticket}");
            //}
            //catch (MT4Exception e)
            //{
            //    Console.WriteLine($"Order Placing Error #{e.ErrorCode}:{e.Message}");
            //}
            //try
            //{
            //    var ticket = mt4.OrderSend("AUDCAD-STD",
            //        TradeOperation.OP_BUY,
            //        0.01, bid, 2, 0, 0,
            //        "Order_Sell_Demo", 0,
            //        MT4.NoExpiration
            //        );
            //    Console.WriteLine($"New Buy_Order ID: {ticket}");
            //}
            //catch (MT4Exception e)
            //{
            //    Console.WriteLine($"Order Placing Error #{e.ErrorCode}:{e.Message}");
            //}


            //
            Console.ReadLine();
        }
Beispiel #31
0
            private bool CheckHedges(Stack <IOrderInfo> bStack)
            {
                Stack <IOrderInfo> cbStack  = null;
                Stack <IOrderInfo> hdgStack = null;
                long tmpTicket;

                if (_closedBy.TryGetValue(bStack.Peek().Ticket(), out tmpTicket))
                {
                    cbStack = bStack;
                    if (_sellAtTop.ContainsKey(tmpTicket))
                    {
                        hdgStack = _sellSide.FirstOrDefault(sellStack => sellStack.Peek().Ticket() == tmpTicket);
                    }
                }
                if (_hedgedBy.TryGetValue(bStack.Peek().Ticket(), out tmpTicket))
                {
                    hdgStack = bStack;
                    if (_sellAtTop.ContainsKey(tmpTicket))
                    {
                        cbStack = _sellSide.FirstOrDefault(sellStack => sellStack.Peek().Ticket() == tmpTicket);
                    }
                }
                if (cbStack != null && hdgStack != null)
                {
                    var cbOrder  = cbStack.Pop();
                    var hdgOrder = hdgStack.Pop();
                    //
                    _history.Add(hdgOrder);
                    _history.Add(cbOrder);
                    //
                    IOrderInfo cbNext  = null;
                    IOrderInfo hdgNext = null;
                    //
                    Dictionary <long, bool> cbTop  = cbOrder.GetTradeOperation() == TradeOperation.OP_BUY ? _buyAtTop : _sellAtTop;
                    Dictionary <long, bool> hdgTop = hdgOrder.GetTradeOperation() == TradeOperation.OP_BUY ? _buyAtTop : _sellAtTop;
                    cbTop.Remove(cbOrder.Ticket());
                    hdgTop.Remove(hdgOrder.Ticket());
                    if (cbStack.Count > 0)
                    {
                        cbTop[(cbNext = cbStack.Peek()).Ticket()] = true;
                    }
                    if (hdgStack.Count > 0)
                    {
                        hdgTop[(hdgNext = hdgStack.Peek()).Ticket()] = true;
                    }
                    //
                    cbOrder.SetClosedBy(hdgOrder);
                    if (cbNext == null && hdgNext == null)
                    {
                        //check live orders for next
                        var cbC  = new OComparator(cbOrder);
                        var hdgC = new OComparator(hdgOrder);
                        cbNext =
                            _live.FirstOrDefault(
                                order => order.Ticket() > cbOrder.Ticket() && cbC.IsSameLiveOrder(order));
                        hdgNext =
                            _live.FirstOrDefault(
                                order => order.Ticket() > hdgOrder.Ticket() && hdgC.IsSameLiveOrder(order));
                    }
                    var next = cbNext == null
                        ? hdgNext
                        : (hdgNext == null
                            ? cbNext
                            : (cbNext.Ticket() > hdgNext.Ticket() ? hdgNext : cbNext)); // use minimal ticket number for next order
                    if (next != null)
                    {
                        if (ReferenceEquals(next, cbNext))
                        {
                            cbOrder.SetNext(next);
                        }
                        if (ReferenceEquals(next, hdgNext))
                        {
                            hdgOrder.SetNext(next);
                        }
                    }
                    //
                    // remove empty stack from a side
                    if (cbStack.Count == 0)
                    {
                        (cbOrder.GetTradeOperation() == TradeOperation.OP_BUY ? _buySide : _sellSide).Remove(cbStack);
                    }
                    if (hdgStack.Count == 0)
                    {
                        (hdgOrder.GetTradeOperation() == TradeOperation.OP_BUY ? _buySide : _sellSide).Remove(hdgStack);
                    }
                    //
                    return(true);
                }
                return(false);
            }
Beispiel #32
0
        internal void MasterOrderCreated(IOrderInfo masterOrder)
        {
            RefreshRates();
            double orderPrice = Marketinfo(masterOrder.GetSymbol(),
                                           (masterOrder.GetTradeOperation() == TradeOperation.OP_BUY)
                                                      ? MarketInfo.MODE_ASK
                                                      : MarketInfo.MODE_BID);
            TradeOperation orderType = masterOrder.GetTradeOperation();

            Console.WriteLine("Creating an order - order.closePrice: {0} market.bid: {1} market.ask: {2} order.OrderType: {3}", masterOrder.GetClosePrice(), Marketinfo(masterOrder.GetSymbol(), MarketInfo.MODE_BID), Marketinfo(masterOrder.GetSymbol(), MarketInfo.MODE_ASK), orderType);


            //Info(String.Format("Executing order for account {0}", _acc));

            try {
                int ticket = OrderSend(
                    masterOrder.GetSymbol(),
                    masterOrder.GetTradeOperation(),
                    masterOrder.GetLots(),
                    //masterOrder.GetOpenPrice(), // todo: adjust price to current Bid/Ask if OrderType==OP_BUY/SELL
                    orderPrice,
                    20,
                    masterOrder.GetStopLoss(),
                    masterOrder.GetTakeProfit(),
                    _master.Acc + "@" + _master.Broker + "-> _acc:" + _acc,
                    masterOrder.GetTicket(),
                    masterOrder.GetExpiration(),
                    0
                    );
                if (ticket != 0)
                {
                    _ordersMap.Add(masterOrder.GetTicket(), ticket);
                    Info(String.Format("Master order {0} is mapped to {1}", masterOrder, ticket));
                }
            }
            catch (ErrTradeDisabled)
            {
                Info(String.Format("Trade disabled for accoutn: {0}", _acc));
            }
            catch (ErrInvalidPrice)
            {
                Info(String.Format("## ErrInvalidPrice - Price slippage ## - order.closePrice: {0} market.bid: {1} market.ask: {2} order.OrderType: {3}", masterOrder.GetClosePrice(), Marketinfo(masterOrder.GetSymbol(), MarketInfo.MODE_BID), Marketinfo(masterOrder.GetSymbol(), MarketInfo.MODE_ASK), orderType));
            }

            /*
             * catch(ErrInvalidPrice)
             * {
             * Info(String.Format("Price invalid: {0} ", masterOrder.GetOpenPrice()));
             *
             * }
             * catch(ErrInvalidTradeVolume)
             * {
             * Info(String.Format("Trade volume invalid: {0} ", masterOrder.GetLots()));
             *
             * }
             * catch(ErrTradeDisabled)
             * {
             * Info(String.Format("Trade disabled!!"));
             *
             * }
             * catch(ErrOffQuotes)
             * {
             * Info(String.Format("This trade is off quotes!!"));
             *
             * }
             **/
        }
Beispiel #33
0
		/// <summary>
		/// Initializes a new instance of the <see cref="OrderLine"/> class.
		/// </summary>
		/// <param name="productInfo">The product information.</param>
		/// <param name="order">The order.</param>
		public OrderLine(ProductInfo productInfo, IOrderInfo order)
		{
			Order = order;
			productInfo.Order = order;
			ProductInfo = productInfo;
		}
Beispiel #34
0
        public override void Refresh()
        {
            IScorpionDataProvider dataSession = null;

            try
            {
                dataSession = DataProviderFactory.GetSession();

                info = dataSession.GetOrder(info.Identifier);
            }
            catch
            {
                throw;
            }
            finally
            {
                if (dataSession != null)
                    dataSession.Dispose();
            }
        }
Beispiel #35
0
 internal void AddNewOrder(IOrderInfo o)
 {
     o.SetWasEverLiveOrder(true);
     NewOrders.Add(o);
 }
        public static ProductInfo CreateProductInfo(int productPriceInCents, int itemCount, decimal vat = 19, DiscountProduct discount = null, IOrderInfo order = null)
        {
            var productInfo = new ProductInfo();

            productInfo.IsDiscounted         = discount == null;
            productInfo.OriginalPriceInCents = productPriceInCents;
            productInfo.Ranges    = new List <Range>();
            productInfo.Vat       = vat;
            productInfo.ItemCount = itemCount;
            productInfo.Tags      = new string[0];
            if (order != null)
            {
                order.OrderLines = new List <OrderLine> {
                    new OrderLine(productInfo, order)
                };
            }
            productInfo.Order = order ?? CreateOrderInfo(productInfo);
            if (discount != null)
            {
                SetProductDiscountOnProductInfo(productInfo, discount);
            }
            return(productInfo);
        }
Beispiel #37
0
        public void RegisterPayment(ref string identifier, DateTime timestamp, string method, string transactionIdentifier, string transactionType, string status, string statusShortMessage, string statusLongMessage, string paymentType, string currency, decimal amount, decimal fee, decimal finalAmount, decimal taxAmount, decimal exchangeRate, string receiptIdentifier, IDictionary<string, string> attributes)
        {
            IScorpionDataProvider dataStore = base.DataProviderFactory.GetSession();

            dataStore.BeginTransaction();

            try
            {
                if (string.IsNullOrEmpty(identifier))
                    identifier = GetNewPaymentIdentifier();
                else
                    if (dataStore.PaymentExists(identifier))
                        throw new OrderExists();

                dataStore.InsertPayment(identifier, info.Identifier, timestamp, method, transactionIdentifier, transactionType, status, statusShortMessage, statusLongMessage, paymentType, currency, amount, fee, finalAmount, taxAmount, exchangeRate, receiptIdentifier, SecurityManager.CurrentUser.Identity.Identifier);

                foreach( KeyValuePair<string, string> attribute in attributes)
                    dataStore.SetPaymentAttribute(identifier, attribute.Key, attribute.Value, SecurityManager.CurrentUser.Identity.Identifier);

                dataStore.CommitTransaction();

                info = dataStore.GetOrder(info.Identifier);
            }
            catch
            {
                dataStore.RollbackTransaction();
                throw;
            }
            finally
            {
                dataStore.Dispose();
            }
        }