private void DelOrder(Order order)
 {
     lock (_locker)
     {
         _myOrders.Remove(order);
     }
 }
Exemple #2
0
        /// <summary>
        /// execute orders in the exchange
        /// исполнить ордер на бирже
        /// </summary>
        public async void ExecuteOrder(Order order)
        {
            if (_isConnected == false)
            {
                return;
            }

            _orders.Add(order);

            try
            {
                string expiry = ConvertDateTimeToAcceptDateFormat(DateTime.Now.AddMonths(1));

                decimal volume = order.Volume;

                if (order.Side == Side.Sell)
                {
                    volume = -order.Volume;
                }
                string price = order.Price.ToString(new CultureInfo("en-US"));

                Instrument myInstrument = _allInstruments.Find(inst => inst.name == order.SecurityNameCode);

                // create new pending order
                var request = new LimitOrderRequest(myInstrument)
                {
                    instrument  = order.SecurityNameCode,
                    units       = Convert.ToInt64(volume),
                    timeInForce = TimeInForce.GoodUntilDate,
                    gtdTime     = expiry,
                    price       = price.ToDecimal(),

                    clientExtensions = new ClientExtensions()
                    {
                        id      = order.NumberUser.ToString(),
                        comment = "",
                        tag     = ""
                    },
                    tradeClientExtensions = new ClientExtensions()
                    {
                        id      = order.NumberUser.ToString(),
                        comment = "",
                        tag     = ""
                    }
                };

                var response = await Rest20.PostOrderAsync(Credentials.GetDefaultCredentials().DefaultAccountId, request);

                var orderTransaction = response.orderCreateTransaction;

                if (orderTransaction.id > 0)
                {
                    order.NumberMarket = orderTransaction.id.ToString();
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
            }
        }
Exemple #3
0
        public void CancelOrder(Order order)
        {
            _ordersAllReadyCanseled.Add(order);

            QuikSharp.DataStructures.Transaction.Order qOrder = new QuikSharp.DataStructures.Transaction.Order();

            qOrder.SecCode   = order.SecurityNameCode.Split('_')[0];
            qOrder.Account   = order.PortfolioNumber;
            qOrder.ClassCode = _securities.Find(sec => sec.Name == order.SecurityNameCode).NameClass;

            if (order.NumberMarket == "")
            {
                qOrder.OrderNum = 0;
            }
            else
            {
                qOrder.OrderNum = Convert.ToInt64(order.NumberMarket);
            }
            //qOrder.OrderNum = Convert.ToInt64(order.NumberMarket);

            lock (_serverLocker)
            {
                var res = QuikLua.Orders.KillOrder(qOrder).Result;
            }
        }
Exemple #4
0
        /// <summary>
        /// отозвать ордер
        /// </summary>
        public void CanselOrder(Order order)
        {
            if (string.IsNullOrWhiteSpace(order.NumberMarket))
            {
                return;
            }
            if (string.IsNullOrEmpty(order.NumberMarket))
            {
                return;
            }
            try
            {
                var openOrders = Rest20.GetPendingOrderListAsync(Credentials.GetDefaultCredentials().DefaultAccountId);

                while (!openOrders.IsCanceled &&
                       !openOrders.IsCompleted &&
                       !openOrders.IsFaulted)
                {
                    Thread.Sleep(20);
                }


                for (int i = 0; i < openOrders.Result.Count; i++)
                {
                    if (openOrders.Result[i].id == Convert.ToInt64(order.NumberMarket))
                    {
                        Rest20.CancelOrderAsync(Credentials.GetDefaultCredentials().DefaultAccountId, openOrders.Result[i].id);
                    }
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
            }
        }
Exemple #5
0
 /// <summary>
 /// исполнить ордер
 /// </summary>
 public void ExecuteOrder(Order order)
 {
     if (_orders == null)
     {
         _orders = new List <Order>();
     }
     _orders.Add(order);
     order.TimeCreate = ServerTime;
     _ordersToExecute.Enqueue(order);
 }
Exemple #6
0
        /// <summary>
        /// cancel order
        /// отменить ордер
        /// </summary>
        public void CanselOrder(Order order)
        {
            string cmd = "<command id=\"cancelorder\">";

            cmd += "<transactionid>" + order.NumberUser + "</transactionid>";
            cmd += "</command>";

            // отправка команды
            string res = _client.ConnectorSendCommand(cmd);

            if (!res.StartsWith("<result success=\"true\""))
            {
                SendLogMessage(res, LogMessageType.Error);
            }
        }
Exemple #7
0
        void _ibClient_NewOrderEvent(Order order)
        {
            try
            {
                if (_orders == null)
                {
                    _orders = new List <Order>();
                }

                _ordersToSend.Enqueue(order);
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
            }
        }
        public void CancelLimitOrder(OsEngine.Entity.Order order)
        {
            var cancelOrders = new CancelLimitOrderRequest
            {
                ExpireControl = new RequestExpired
                {
                    Now = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds,
                    Ttl = ttl
                },
                CurrencyPair = order.SecurityNameCode.Replace("_", "/"),
                Id           = Convert.ToInt64(order.NumberMarket)
            };

            string token = "CancelOrder_" + order.NumberUser;

            SendAuthMessage(_secKey, token, WsRequestMetaData.WsRequestMsgType.CancelLimitOrder, cancelOrders);
        }
Exemple #9
0
        /// <summary>
        /// send order to exchange
        /// выслать ордер на биржу
        /// </summary>
        public void SendOrder(Order order)
        {
            string side = order.Side == Side.Buy ? "B" : "S";

            var needSec = _securities.Find(s => s.Name == order.SecurityNameCode);

            string cmd = "<command id=\"neworder\">";

            cmd += "<security>";
            cmd += "<board>" + needSec.NameClass + "</board>";
            cmd += "<seccode>" + needSec.Name + "</seccode>";
            cmd += "</security>";
            cmd += "<union>" + _clients[0].Union + "</union>";
            cmd += "<price>" + order.Price + "</price>";
            cmd += "<quantity>" + order.Volume + "</quantity>";
            cmd += "<buysell>" + side + "</buysell>";
            cmd += "<brokerref>" + order.NumberUser + "</brokerref>";
            cmd += "<unfilled> PutInQueue </unfilled>";

            cmd += "</command>";

            // sending command / отправка команды
            string res = _client.ConnectorSendCommand(cmd);

            Result data;
            var    formatter = new XmlSerializer(typeof(Result));

            using (StringReader fs = new StringReader(res))
            {
                data = (Result)formatter.Deserialize(fs);
            }

            //<result success="true" transactionid="12445626"/>
            if (data.Success != "true")
            {
                order.State = OrderStateType.Fail;
            }
            else
            {
                order.NumberUser = int.Parse(data.Transactionid);
                order.State      = OrderStateType.Pending;
            }
            order.TimeCallBack = ServerTime;

            MyOrderEvent?.Invoke(order);
        }
Exemple #10
0
        void _newOrderEvent(Order order)
        {
            try
            {
                if (_orders == null)
                {
                    _orders = new List <Order>();
                }

                order.ServerType = ServerType.Kraken;
                _ordersToSend.Enqueue(order);
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
            }
        }
Exemple #11
0
        public void SendOrder(Order order, string genId)
        {
            string needId = genId;

            string side = order.Side == Side.Buy ? "buy" : "sell";

            string request =
                $"{{\"method\": \"newOrder\", \"params\": {{ \"clientOrderId\": \"{needId}\", \"symbol\": \"{order.SecurityNameCode}\", \"side\": \"{side}\",";

            if (order.TypeOrder == OrderPriceType.Limit)
            {
                request += $"\"type\": \"limit\", \"price\": \"{order.Price.ToString(CultureInfo.InvariantCulture).Replace(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator, ".")}\",";
            }

            request += $"\"quantity\": \"{order.Volume.ToString(CultureInfo.InvariantCulture).Replace(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator, ".")}\" }}, \"id\": 200 }}";

            _wsClient.Send(request);
        }
Exemple #12
0
        public void SendOrder(OsEngine.Entity.Order order)
        {
            var newOrder = new protobuf.ws.PutLimitOrderRequest
            {
                CurrencyPair  = order.SecurityNameCode.Replace('_', '/'),
                Amount        = order.Volume.ToString(),
                order_type    = order.Side == Side.Sell ? protobuf.ws.PutLimitOrderRequest.OrderType.Ask : protobuf.ws.PutLimitOrderRequest.OrderType.Bid,
                Price         = order.Price.ToString(),
                ExpireControl = new protobuf.ws.RequestExpired
                {
                    Now = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds,
                    Ttl = ttl
                }
            };

            string token = "NewOrder" + "_" + order.NumberUser.ToString();

            SendAuthMessage(_secKey, token, protobuf.ws.WsRequestMetaData.WsRequestMsgType.PutLimitOrder, newOrder);
        }
Exemple #13
0
        public void SendOrder(Order order)
        {
            QuikSharp.DataStructures.Transaction.Order qOrder = new QuikSharp.DataStructures.Transaction.Order();

            qOrder.SecCode   = order.SecurityNameCode.Split('_')[0];
            qOrder.Account   = order.PortfolioNumber;
            qOrder.ClassCode = _securities.Find(sec => sec.Name == order.SecurityNameCode).NameClass;
            qOrder.Quantity  = Convert.ToInt32(order.Volume);
            qOrder.Operation = order.Side == Side.Buy ? Operation.Buy : Operation.Sell;
            qOrder.Price     = order.Price;
            qOrder.Comment   = order.NumberUser.ToString();

            lock (_serverLocker)
            {
                var res = QuikLua.Orders.CreateOrder(qOrder).Result;

                if (res > 0)
                {
                    order.NumberUser = Convert.ToInt32(res);

                    if (MyOrderEvent != null)
                    {
                        MyOrderEvent(order);
                    }
                }

                if (res < 0)
                {
                    order.State = OrderStateType.Fail;
                    if (MyOrderEvent != null)
                    {
                        MyOrderEvent(order);
                    }
                }
            }
        }
Exemple #14
0
 /// <summary>
 /// отменить ордер
 /// </summary>
 public void CanselOrder(Order order)
 {
     _ordersToCansel.Enqueue(order);
 }
Exemple #15
0
        /// <summary>
        /// got order information
        /// пришла информация об ордерах
        /// </summary>
        private void ClientOnMyOrderEvent(List <TransaqEntity.Order> orders)
        {
            foreach (var order in orders)
            {
                try
                {
                    if (order.Orderno == "0")
                    {
                        continue;
                    }

                    Order newOrder = new Order();
                    newOrder.SecurityNameCode = order.Seccode;
                    newOrder.NumberUser       = Convert.ToInt32(order.Transactionid);
                    newOrder.NumberMarket     = order.Orderno;
                    newOrder.TimeCallBack     = order.Time != null?DateTime.Parse(order.Time) : ServerTime;

                    newOrder.Side            = order.Buysell == "B" ? Side.Buy : Side.Sell;
                    newOrder.Volume          = Convert.ToDecimal(order.Quantity);
                    newOrder.Price           = Convert.ToDecimal(order.Price.Replace(".", ","));
                    newOrder.ServerType      = ServerType.Transaq;
                    newOrder.PortfolioNumber = order.Union;

                    if (order.Status == "active")
                    {
                        newOrder.State = OrderStateType.Activ;
                    }
                    else if (order.Status == "cancelled" ||
                             order.Status == "expired" ||
                             order.Status == "disabled" ||
                             order.Status == "removed")
                    {
                        newOrder.State = OrderStateType.Cancel;
                    }
                    else if (order.Status == "matched")
                    {
                        newOrder.State = OrderStateType.Done;
                    }
                    else if (order.Status == "denied" ||
                             order.Status == "rejected" ||
                             order.Status == "failed" ||
                             order.Status == "refused")
                    {
                        newOrder.State = OrderStateType.Fail;
                    }
                    else if (order.Status == "forwarding" ||
                             order.Status == "wait" ||
                             order.Status == "watching")
                    {
                        newOrder.State = OrderStateType.Pending;
                    }
                    else
                    {
                        newOrder.State = OrderStateType.None;
                    }

                    if (MyOrderEvent != null)
                    {
                        MyOrderEvent(newOrder);
                    }
                }
                catch (Exception e)
                {
                    SendLogMessage(e.ToString(), LogMessageType.Error);
                }
            }
        }
Exemple #16
0
        void _transactionsSession_DataReceived(OkonkwoOandaV20.TradeLibrary.DataTypes.Stream.TransactionStreamResponse data)
        {
            if (data.transaction.type == "LIMIT_ORDER")
            {
                LimitOrderTransaction order = (LimitOrderTransaction)data.transaction;

                Order newOrder = new Order();
                newOrder.NumberUser       = Convert.ToInt32(order.clientExtensions.id);
                newOrder.NumberMarket     = order.id.ToString();
                newOrder.SecurityNameCode = order.instrument;
                newOrder.Price            = Convert.ToDecimal(order.price);
                newOrder.TimeCallBack     = DateTime.Parse(order.time);
                newOrder.State            = OrderStateType.Activ;

                if (NewOrderEvent != null)
                {
                    NewOrderEvent(newOrder);
                }
            }
            else if (data.transaction.type == "LIMIT_ORDER_REJECT")
            {
                LimitOrderRejectTransaction order = (LimitOrderRejectTransaction)data.transaction;

                Order newOrder = new Order();
                newOrder.NumberUser       = Convert.ToInt32(order.clientExtensions.id);
                newOrder.NumberMarket     = order.id.ToString();
                newOrder.SecurityNameCode = order.instrument;
                newOrder.Price            = Convert.ToDecimal(order.price);
                newOrder.State            = OrderStateType.Fail;
                newOrder.TimeCallBack     = DateTime.Parse(order.time);

                if (NewOrderEvent != null)
                {
                    NewOrderEvent(newOrder);
                }
            }
            else if (data.transaction.type == "ORDER_FILL")
            {
                OrderFillTransaction order = (OrderFillTransaction)data.transaction;

                MyTrade trade = new MyTrade();
                trade.NumberOrderParent = order.clientOrderID;
                trade.NumberTrade       = order.id.ToString();
                trade.Price             = Convert.ToDecimal(order.price);
                trade.Volume            = Convert.ToDecimal(order.units);
                trade.Time             = DateTime.Parse(order.time);
                trade.SecurityNameCode = order.instrument;

                Order myOrder = _orders.Find(o => o.NumberUser.ToString() == order.clientOrderID);

                if (myOrder == null)
                {
                    return;
                }
                trade.Volume = myOrder.Volume;

                if (order.units == 1)
                {
                    trade.Side = Side.Buy;
                }
                else
                {
                    trade.Side = Side.Sell;
                }

                if (NewMyTradeEvent != null)
                {
                    NewMyTradeEvent(trade);
                }
            }
            else if (data.transaction.type == "SystemOrderReject")
            {
                Order newOrder = new Order();
                // newOrder.NumberUser = order.NumberUser;
                newOrder.State = OrderStateType.Fail;
                //trade.Time = DateTime.Parse(order.time);
                if (NewOrderEvent != null)
                {
                    NewOrderEvent(newOrder);
                }
            }
            else if (data.transaction.type == "ORDER_CANCEL")
            {
                OrderCancelTransaction order = (OrderCancelTransaction)data.transaction;

                Order newOrder = new Order();
                newOrder.NumberUser   = Convert.ToInt32(order.clientOrderID);
                newOrder.State        = OrderStateType.Cancel;
                newOrder.TimeCallBack = DateTime.Parse(order.time);
                newOrder.TimeCancel   = newOrder.TimeCallBack;
                if (NewOrderEvent != null)
                {
                    NewOrderEvent(newOrder);
                }
            }
        }
Exemple #17
0
        private void EventsOnOnOrder(QuikSharp.DataStructures.Transaction.Order qOrder)
        {
            lock (orderLocker)
            {
                try
                {
                    if (qOrder.TransID == 0)
                    {
                        return;
                    }

                    Order order = new Order();
                    order.NumberUser       = Convert.ToInt32(qOrder.TransID); //Convert.qOrder.OrderNum;TransID
                    order.NumberMarket     = qOrder.OrderNum.ToString(new CultureInfo("ru-RU"));
                    order.TimeCallBack     = ServerTime;
                    order.SecurityNameCode = qOrder.SecCode + "_" + qOrder.ClassCode;
                    order.Price            = qOrder.Price;
                    order.Volume           = qOrder.Quantity;
                    order.VolumeExecute    = qOrder.Quantity - qOrder.Balance;
                    order.PortfolioNumber  = qOrder.Account;
                    order.TypeOrder        = qOrder.Flags.ToString().Contains("IsLimit")
                        ? OrderPriceType.Limit
                        : OrderPriceType.Market;
                    order.ServerType = ServerType.QuikLua;

                    if (qOrder.State == State.Active)
                    {
                        order.State        = OrderStateType.Activ;
                        order.TimeCallBack = new DateTime(qOrder.Datetime.year, qOrder.Datetime.month,
                                                          qOrder.Datetime.day,
                                                          qOrder.Datetime.hour, qOrder.Datetime.min, qOrder.Datetime.sec);
                    }
                    else if (qOrder.State == State.Completed)
                    {
                        order.State         = OrderStateType.Done;
                        order.VolumeExecute = qOrder.Quantity;
                        order.TimeDone      = order.TimeCallBack;
                    }
                    else if (qOrder.State == State.Canceled)
                    {
                        order.TimeCancel = new DateTime(qOrder.WithdrawDatetime.year, qOrder.WithdrawDatetime.month,
                                                        qOrder.WithdrawDatetime.day,
                                                        qOrder.WithdrawDatetime.hour, qOrder.WithdrawDatetime.min, qOrder.WithdrawDatetime.sec);
                        order.State         = OrderStateType.Cancel;
                        order.VolumeExecute = 0;
                    }
                    else if (qOrder.Balance != 0)
                    {
                        order.State         = OrderStateType.Patrial;
                        order.VolumeExecute = qOrder.Quantity - qOrder.Balance;
                    }

                    if (_ordersAllReadyCanseled.Find(o => o.NumberUser == qOrder.TransID) != null)
                    {
                        order.State      = OrderStateType.Cancel;
                        order.TimeCancel = order.TimeCallBack;
                    }

                    if (qOrder.Operation == Operation.Buy)
                    {
                        order.Side = Side.Buy;
                    }
                    else
                    {
                        order.Side = Side.Sell;
                    }

                    if (MyOrderEvent != null)
                    {
                        MyOrderEvent(order);
                    }
                }
                catch (Exception error)
                {
                    SendLogMessage(error.ToString(), LogMessageType.Error);
                }
            }
        }