/// <summary>
        /// создать закрывающий ордер для сделки
        /// </summary>
        public Order CreateCloseOrderForDeal(Position deal, decimal price, OrderPriceType priceType, TimeSpan timeLife)
        {
            Side direction;

            if (deal.Direction == Side.Buy)
            {
                direction = Side.Sell;
            }
            else
            {
                direction = Side.Buy;
            }

            int volume = deal.OpenVolume;

            if (volume == 0)
            {
                return(null);
            }

            Order newOrder = new Order();

            newOrder.NumberUser = NumberGen.GetNumberOrder();
            newOrder.Side       = direction;
            newOrder.Price      = price;
            newOrder.Volume     = volume;
            newOrder.TypeOrder  = priceType;
            newOrder.LifeTime   = timeLife;

            return(newOrder);
        }
示例#2
0
        /// <summary>
        /// создать менеджера роботов
        /// </summary>
        /// <param name="hostChart">область для чарта</param>
        /// <param name="hostGlass">область для стакана</param>
        /// <param name="hostOpenDeals">область для таблицы открытых сделок</param>
        /// <param name="hostCloseDeals">область для таблицы закрытых сделок</param>
        /// <param name="hostAllDeals">область всех сделок</param>
        /// <param name="hostLogBot">область для бот лога</param>
        /// <param name="hostLogPrime">область для прайм лога</param>
        /// <param name="rectangleAroundChart">квадрат за чартом</param>
        /// <param name="hostAlerts">область для алертов</param>
        /// <param name="tabPanel">панель с роботами</param>
        /// <param name="tabBotTab">панель робота с вкладками инструментов</param>
        /// <param name="textBoxLimitPrice">текстБокс с ценой лимитника при вводе заявки</param>
        /// <param name="gridChartControlPanel">грид для панели управления чартом</param>
        /// <param name="startProgram">тип программы который запросил создание класса</param>
        public OsTraderMaster(WindowsFormsHost hostChart, WindowsFormsHost hostGlass, WindowsFormsHost hostOpenDeals,
                              WindowsFormsHost hostCloseDeals, WindowsFormsHost hostAllDeals, WindowsFormsHost hostLogBot, WindowsFormsHost hostLogPrime, Rectangle rectangleAroundChart, WindowsFormsHost hostAlerts,
                              TabControl tabPanel, TabControl tabBotTab, TextBox textBoxLimitPrice, Grid gridChartControlPanel, StartProgram startProgram)
        {
            NumberGen.GetNumberOrder(startProgram);
            _startProgram = startProgram;

            if (_startProgram == StartProgram.IsTester)
            {
                _typeWorkKeeper = ConnectorWorkType.Tester;
                ((TesterServer)ServerMaster.GetServers()[0]).TestingStartEvent += StrategyKeeper_TestingStartEvent;
                ((TesterServer)ServerMaster.GetServers()[0]).TestingFastEvent  += StrategyKeeper_TestingFastEvent;
                ((TesterServer)ServerMaster.GetServers()[0]).TestingEndEvent   += StrategyKeeper_TestingEndEvent;
            }

            if (_startProgram != StartProgram.IsTester)
            {
                ServerMaster.ActivateAutoConnection();
            }

            ServerMaster.LogMessageEvent += SendNewLogMessage;

            _tabBotTab = tabBotTab;

            if (_tabBotTab.Items != null)
            {
                _tabBotTab.Items.Clear();
            }
            _textBoxLimitPrice     = textBoxLimitPrice;
            _hostChart             = hostChart;
            _hostGlass             = hostGlass;
            _hostOpenDeals         = hostOpenDeals;
            _hostCloseDeals        = hostCloseDeals;
            _hostAllDeals          = hostAllDeals;
            _hostboxLog            = hostLogBot;
            _rectangleAroundChart  = rectangleAroundChart;
            _hostAlerts            = hostAlerts;
            _gridChartControlPanel = gridChartControlPanel;

            _tabBotNames = tabPanel;
            _tabBotNames.Items.Clear();

            _riskManager = new RiskManager.RiskManager("GlobalRiskManager", _startProgram);
            _riskManager.RiskManagerAlarmEvent += _riskManager_RiskManagerAlarmEvent;
            _riskManager.LogMessageEvent       += SendNewLogMessage;
            _globalController = new GlobalPosition(_hostAllDeals, _startProgram);
            _globalController.LogMessageEvent += SendNewLogMessage;

            _log = new Log("Prime", _startProgram);
            _log.StartPaint(hostLogPrime);
            _log.Listen(this);
            _hostLogPrime = hostLogPrime;

            SendNewLogMessage("Запуск OsTraderMaster. Включение программы.", LogMessageType.User);

            Load();
            _tabBotNames.SelectionChanged += _tabBotControl_SelectionChanged;
            ReloadRiskJournals();
            _globalController.StartPaint();
        }
示例#3
0
        public void SendOrder(ServerType server, string security, string portfolio, decimal price, decimal volume, Side orderSide)
        {
            IServer myServer = null;

            for (int i = 0; i < Servers.Count; i++)
            {
                if (Servers[i].ServerType == server)
                {
                    myServer = Servers[i];
                    break;
                }
            }
            if (myServer == null)
            {
                return;
            }
            Order order = new Order();

            order.SecurityNameCode = security;
            order.PortfolioNumber  = portfolio;
            order.Price            = price;
            order.Volume           = volume;
            order.Side             = orderSide;
            order.NumberUser       = NumberGen.GetNumberOrder(this.StartProgram);

            myServer.ExecuteOrder(order);
        }
示例#4
0
        /// <summary>
        /// generete my trade from order
        /// сгенерировать мои трейды из ордера
        /// </summary>
        /// <param name="order"></param>
        private void GenerateTrades(KrakenOrder order)
        {
            Order osOrder = _osEngineOrders.Find(ord => ord.NumberMarket == order.TxId);

            MyTrade newTrade = new MyTrade();

            newTrade.NumberOrderParent = order.TxId;
            newTrade.NumberTrade       = NumberGen.GetNumberOrder(StartProgram.IsOsTrader).ToString();

            newTrade.Side = osOrder.Side;
            if (order.AveragePrice != null &&
                order.AveragePrice != 0)
            {
                newTrade.Price = Convert.ToDecimal(order.AveragePrice);
            }
            else
            {
                newTrade.Price = osOrder.Price;
            }

            newTrade.Volume           = order.Volume;
            newTrade.SecurityNameCode = osOrder.SecurityNameCode;

            if (NewMyTradeEvent != null)
            {
                NewMyTradeEvent(newTrade);
            }
        }
示例#5
0
        /// <summary>
        /// convert Os.Engine order to string for canceling in QUIK
        /// преобразовать ордер Os.Engine в строку отзыва ордера Квик
        /// </summary>
        private string ConvertToKillQuikOrder(Order order)
        {
            Portfolio myPortfolio = _portfolios.Find(por => por.Number == order.PortfolioNumber);
            Security  mySecurity  = _securities.Find(sec => sec.Name == order.SecurityNameCode);

            if (myPortfolio == null ||
                mySecurity == null)
            {
                return(null);
            }


            // CLASSCODE = TQBR; SECCODE = RU0009024277; TRANS_ID = 5; ACTION = KILL_ORDER; ORDER_KEY = 503983;

            string accaunt;

            string codeClient;

            if (myPortfolio.Number.Split('@').Length == 1)
            {
                accaunt    = myPortfolio.Number;
                codeClient = "";
            }
            else
            {
                accaunt    = myPortfolio.Number.Split('@')[0];
                codeClient = myPortfolio.Number.Split('@')[1];
            }

            string command;

            if (codeClient == "")
            {
                command =
                    "TRANS_ID=" + NumberGen.GetNumberOrder(StartProgram.IsOsTrader) +
                    "; ACCOUNT=" + accaunt +
                    "; SECCODE=" + mySecurity.Name +
                    "; CLASSCODE=" + mySecurity.NameClass +
                    "; ACTION=KILL_ORDER" +
                    "; ORDER_KEY=" + order.NumberMarket +
                    ";";
            }
            else
            {
                command =
                    "TRANS_ID=" + NumberGen.GetNumberOrder(StartProgram.IsOsTrader) +
                    "; ACCOUNT=" + accaunt +
                    "; CLIENT_CODE=" + codeClient +
                    "; SECCODE=" + mySecurity.Name +
                    "; CLASSCODE=" + mySecurity.NameClass +
                    "; ACTION=KILL_ORDER" +
                    "; ORDER_KEY=" + order.NumberMarket +
                    ";";
            }

            return(command);
        }
示例#6
0
        private void GenerateTrades(KrakenOrder order)
        {
            return;

            Order osOrder = _osEngineOrders.Find(ord => ord.NumberMarket == order.TxId);

            if (order.Status == null)
            {
                return;
            }

            if (order.Status != "closed")
            {
                if (osOrder.VolumeExecute == 0)
                {
                    return;
                }
            }


            MyTrade newTrade = new MyTrade();

            newTrade.NumberOrderParent = order.TxId;
            newTrade.NumberTrade       = NumberGen.GetNumberOrder(StartProgram.IsOsTrader).ToString();

            newTrade.Side = osOrder.Side;
            if (order.AveragePrice != null &&
                order.AveragePrice != 0)
            {
                newTrade.Price = Convert.ToDecimal(order.AveragePrice);
            }
            else
            {
                newTrade.Price = osOrder.Price;
            }

            if (order.VolumeExecuted != null &&
                order.VolumeExecuted != 0)
            {
                newTrade.Volume = order.VolumeExecuted.ToString().ToDecimal();
            }
            else
            {
                newTrade.Volume = order.Volume.ToString().ToDecimal();
            }


            newTrade.SecurityNameCode = osOrder.SecurityNameCode;

            if (MyTradeEvent != null)
            {
                MyTradeEvent(newTrade);
            }
        }
示例#7
0
        private void EventsOnOnTrade(QuikSharp.DataStructures.Transaction.Trade qTrade)
        {
            lock (myTradeLocker)
            {
                try
                {
                    MyTrade trade = new MyTrade();
                    trade.NumberTrade       = qTrade.TradeNum.ToString();
                    trade.SecurityNameCode  = qTrade.SecCode + "_" + qTrade.ClassCode;
                    trade.NumberOrderParent = qTrade.OrderNum.ToString();
                    trade.Price             = Convert.ToDecimal(qTrade.Price);
                    trade.Volume            = qTrade.Quantity;
                    trade.Time = new DateTime(qTrade.QuikDateTime.year, qTrade.QuikDateTime.month,
                                              qTrade.QuikDateTime.day, qTrade.QuikDateTime.hour,
                                              qTrade.QuikDateTime.min, qTrade.QuikDateTime.sec, qTrade.QuikDateTime.ms);
                    trade.Side         = qTrade.Flags == OrderTradeFlags.IsSell ? Side.Sell : Side.Buy;
                    trade.MicroSeconds = qTrade.QuikDateTime.mcs;

                    MyTrade tradeWithSameNumber = _myTrades.Find(t => t.NumberTrade == qTrade.TradeNum.ToString());

                    if (tradeWithSameNumber != null)
                    { // нашли трейд с тем же номером.
                        if (tradeWithSameNumber.Time == trade.Time &&
                            tradeWithSameNumber.Price == trade.Price &&
                            tradeWithSameNumber.Volume == trade.Volume &&
                            tradeWithSameNumber.MicroSeconds == trade.MicroSeconds)
                        { // повтор
                            return;
                        }
                        else
                        { // ошибка в КвикШарп по номеру сделки. Даём ей свою
                            trade.NumberTrade = NumberGen.GetNumberOrder(StartProgram.IsOsTrader).ToString();
                        }
                    }

                    _myTrades.Add(trade);

                    if (MyTradeEvent != null)
                    {
                        MyTradeEvent(trade);
                    }

                    if (_myTrades.Count > 1000)
                    {
                        _myTrades.RemoveAt(0);
                    }
                }
                catch (Exception error)
                {
                    SendLogMessage(error.ToString(), LogMessageType.Error);
                }
            }
        }
        /// <summary>
        /// создать ордер
        /// </summary>
        public Order CreateOrder(Side direction, decimal priceOrder, int volume, OrderPriceType priceType, TimeSpan timeLife)
        {
            Order newOrder = new Order();

            newOrder.NumberUser = NumberGen.GetNumberOrder();
            newOrder.Side       = direction;
            newOrder.Price      = priceOrder;
            newOrder.Volume     = volume;
            newOrder.TypeOrder  = priceType;
            newOrder.LifeTime   = timeLife;

            return(newOrder);
        }
示例#9
0
        /// <summary>
        /// создать массив ордеров для айсберга
        /// </summary>
        private void CreateCloseOrders()
        {
            Side side;

            if (_position.Direction == Side.Buy)
            {
                side = Side.Sell;
            }
            else
            {
                side = Side.Buy;
            }


            int realCountOrders = _ordersCount;

            if (realCountOrders > _volume)
            {
                realCountOrders = _volume;
            }

            Order[] orders = new Order[realCountOrders];

            for (int i = 0; i < orders.Length; i++)
            {
                orders[i]                  = new Order();
                orders[i].Side             = side;
                orders[i].LifeTime         = _lifiTime;
                orders[i].Volume           = Convert.ToInt32(Math.Round(Convert.ToDecimal(_volume) / Convert.ToDecimal(realCountOrders)));
                orders[i].Price            = _price;
                orders[i].PortfolioNumber  = _bot.Portfolio.Number;
                orders[i].SecurityNameCode = _bot.Securiti.Name;
                orders[i].NumberUser       = NumberGen.GetNumberOrder();

                if (i + 1 == orders.Length)
                {// если это последний ордер,
                 // считаем отдельно, сколько реально осталось контрактов

                    int realVolume = 0;

                    for (int i2 = 0; i2 < orders.Length - 1; i2++)
                    {
                        realVolume += orders[i2].Volume;
                    }
                    orders[i].Volume = _volume - realVolume;
                }
            }

            _ordersNeadToCreate = orders.ToList();
        }
示例#10
0
        /// <summary>
        /// create an array of orders for iceberg
        /// создать массив ордеров для айсберга
        /// </summary>
        private void CreateCloseOrders()
        {
            Side side;

            if (_position.Direction == Side.Buy)
            {
                side = Side.Sell;
            }
            else
            {
                side = Side.Buy;
            }


            int realCountOrders = _ordersCount;

            if (realCountOrders > _volume)
            {
                realCountOrders = Convert.ToInt32(_volume);
            }

            Order[] orders = new Order[realCountOrders];

            for (int i = 0; i < orders.Length; i++)
            {
                orders[i]                  = new Order();
                orders[i].Side             = side;
                orders[i].LifeTime         = _lifiTime;
                orders[i].Volume           = Convert.ToInt32(Math.Round(Convert.ToDecimal(_volume) / Convert.ToDecimal(realCountOrders)));
                orders[i].Price            = _price;
                orders[i].PortfolioNumber  = _bot.Portfolio.Number;
                orders[i].SecurityNameCode = _bot.Securiti.Name;
                orders[i].NumberUser       = NumberGen.GetNumberOrder(_bot.StartProgram);

                if (i + 1 == orders.Length)
                {
                    decimal realVolume = 0;

                    for (int i2 = 0; i2 < orders.Length - 1; i2++)
                    {
                        realVolume += orders[i2].Volume;
                    }
                    orders[i].Volume = _volume - realVolume;
                }
            }

            _ordersNeadToCreate = orders.ToList();
        }
示例#11
0
        public OsTraderMaster(StartProgram startProgram, WindowsFormsHost hostLogPrime)
        {
            NumberGen.GetNumberOrder(startProgram);
            _startProgram = startProgram;

            if (_startProgram == StartProgram.IsTester)
            {
                _typeWorkKeeper = ConnectorWorkType.Tester;
                ((TesterServer)ServerMaster.GetServers()[0]).TestingStartEvent += StrategyKeeper_TestingStartEvent;
                ((TesterServer)ServerMaster.GetServers()[0]).TestingFastEvent  += StrategyKeeper_TestingFastEvent;
                ((TesterServer)ServerMaster.GetServers()[0]).TestingEndEvent   += StrategyKeeper_TestingEndEvent;
            }

            if (_startProgram != StartProgram.IsTester)
            {
                ServerMaster.ActivateAutoConnection();
            }

            ServerMaster.LogMessageEvent += SendNewLogMessage;


            _riskManager = new RiskManager.RiskManager("GlobalRiskManager", _startProgram);
            _riskManager.RiskManagerAlarmEvent += _riskManager_RiskManagerAlarmEvent;
            _riskManager.LogMessageEvent       += SendNewLogMessage;
            _globalController = new GlobalPosition(_hostAllDeals, _startProgram);
            _globalController.LogMessageEvent += SendNewLogMessage;

            _log = new Log("Prime", _startProgram);
            _log.StartPaint(hostLogPrime);
            _log.Listen(this);
            _hostLogPrime = hostLogPrime;

            SendNewLogMessage(OsLocalization.Trader.Label1, LogMessageType.User);

            Load();
            _tabBotNames.SelectionChanged += _tabBotControl_SelectionChanged;
            ReloadRiskJournals();
            _globalController.StartPaint();

            Master = this;

            if (_startProgram == StartProgram.IsOsTrader && PrimeSettingsMaster.AutoStartApi)
            {
                ApiMaster = new AdminApiMaster(Master);
            }
        }
示例#12
0
        /// <summary>
        /// create order /
        /// создать ордер
        /// </summary>
        public Order CreateOrder(
            Side direction, decimal priceOrder, decimal volume,
            OrderPriceType priceType, TimeSpan timeLife, StartProgram startProgram,
            OrderPositionConditionType positionConditionType)
        {
            Order newOrder = new Order();

            newOrder.NumberUser            = NumberGen.GetNumberOrder(startProgram);
            newOrder.Side                  = direction;
            newOrder.Price                 = priceOrder;
            newOrder.Volume                = volume;
            newOrder.TypeOrder             = priceType;
            newOrder.LifeTime              = timeLife;
            newOrder.PositionConditionType = positionConditionType;

            return(newOrder);
        }
示例#13
0
        /// <summary>
        /// проверить ордера на состояние
        /// </summary>
        public bool GetAllOrders(List <Order> oldOpenOrders)
        {
            List <string> namesSec = new List <string>();

            for (int i = 0; i < oldOpenOrders.Count; i++)
            {
                if (namesSec.Find(name => name.Contains(oldOpenOrders[i].SecurityNameCode)) == null)
                {
                    namesSec.Add(oldOpenOrders[i].SecurityNameCode);
                }
            }


            string endPoint = "/api/v3/allOrders";

            List <HistoryOrderReport> allOrders = new List <HistoryOrderReport>();

            for (int i = 0; i < namesSec.Count; i++)
            {
                var param = new Dictionary <string, string>();
                param.Add("symbol=", namesSec[i].ToUpper());
                //param.Add("&recvWindow=" , "100");
                //param.Add("&limit=", GetNonce());
                param.Add("&limit=", "500");
                //"symbol={symbol.ToUpper()}&recvWindow={recvWindow}"

                var res = CreateQuery(Method.GET, endPoint, param, true);

                HistoryOrderReport[] orders = JsonConvert.DeserializeObject <HistoryOrderReport[]>(res);

                if (orders != null && orders.Length != 0)
                {
                    allOrders.AddRange(orders);
                }
            }

            for (int i = 0; i < oldOpenOrders.Count; i++)
            {
                HistoryOrderReport myOrder = allOrders.Find(ord => ord.orderId == oldOpenOrders[i].NumberMarket);

                if (myOrder == null)
                {
                    continue;
                }

                if (myOrder.status == "NEW")
                { // ордер активен. Ничего не делаем
                    continue;
                }

                else if (myOrder.status == "FILLED" ||
                         myOrder.status == "PARTIALLY_FILLED")
                { // ордер исполнен
                    MyTrade trade = new MyTrade();
                    trade.NumberOrderParent = oldOpenOrders[i].NumberMarket;
                    trade.NumberTrade       = NumberGen.GetNumberOrder(StartProgram.IsOsTrader).ToString();
                    trade.SecurityNameCode  = oldOpenOrders[i].SecurityNameCode;
                    trade.Time = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(myOrder.updateTime));
                    trade.Side = oldOpenOrders[i].Side;

                    if (MyTradeEvent != null)
                    {
                        MyTradeEvent(trade);
                    }
                }
                else
                {
                    Order newOrder = new Order();
                    newOrder.NumberMarket     = oldOpenOrders[i].NumberMarket;
                    newOrder.NumberUser       = oldOpenOrders[i].NumberUser;
                    newOrder.SecurityNameCode = oldOpenOrders[i].SecurityNameCode;
                    newOrder.State            = OrderStateType.Cancel;
                    newOrder.Volume           = oldOpenOrders[i].Volume;
                    newOrder.VolumeExecute    = oldOpenOrders[i].VolumeExecute;
                    newOrder.Price            = oldOpenOrders[i].Price;
                    newOrder.TypeOrder        = oldOpenOrders[i].TypeOrder;
                    newOrder.TimeCallBack     = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(myOrder.updateTime));
                    newOrder.ServerType       = ServerType.Binance;
                    newOrder.PortfolioNumber  = oldOpenOrders[i].PortfolioNumber;

                    if (MyOrderEvent != null)
                    {
                        MyOrderEvent(newOrder);
                    }
                }
            }
            return(true);
        }