/// <summary>
        /// genera un mensaje especifico para Dukascopy
        /// </summary>
        /// <param name="clOrdID"></param>
        /// <param name="price"></param>
        /// <param name="ordType"></param>
        /// <param name="timeInForce"></param>
        /// <param name="symbol"></param>
        /// <param name="orderQty"></param>
        /// <param name="side"></param>
        /// <param name="expireTime"></param>
        /// <param name="account"></param>
        /// <param name="slippage"></param>
        public static void SubmitOrder(ClOrdID clOrdID, decimal?price, OrdType ordType, TimeInForce timeInForce, Symbol symbol, OrderQty orderQty, Side side, ExpireTime expireTime, Account account, decimal?slippage)
        {
            QuickFix44.NewOrderSingle message = new QuickFix44.NewOrderSingle(
                clOrdID,
                side,
                new TransactTime(DateTime.UtcNow),
                ordType);

            if (price.HasValue)
            {
                message.set(new Price((double)price.Value));
            }
            message.set(timeInForce);
            message.set(symbol);
            message.set(orderQty);
            if (expireTime != null)
            {
                message.set(expireTime);
            }
            if (account != null)
            {
                message.set(account);
            }
            if (slippage.HasValue)
            {
                message.setDouble(7011, (double)slippage.Value);
            }

            Credential dukascopyCredential = CredentialFactory.GetCredential(Counterpart.Dukascopy);

            Session.sendToTarget(message, dukascopyCredential.TradingSenderCompID, dukascopyCredential.TradingTargetCompID);
        }
Exemplo n.º 2
0
		internal static OrderType Convert(OrdType type)
		{
			switch (type)
			{
			case OrdType.Market:
				return OrderType.Market;
			case OrdType.Limit:
				return OrderType.Limit;
			case OrdType.Stop:
				return OrderType.Stop;
			case OrdType.StopLimit:
				return OrderType.StopLimit;
			case OrdType.MarketOnClose:
				return OrderType.MarketOnClose;
			default:
				switch (type)
				{
				case OrdType.TrailingStop:
					return OrderType.Trail;
				case OrdType.TrailingStopLimit:
					return OrderType.TrailLimit;
				default:
					throw new ArgumentException(string.Format("OrdType is not supported - {0}", type));
				}
				break;
			}
		}
Exemplo n.º 3
0
        internal static OrderType Convert(OrdType type)
        {
            switch (type)
            {
            case OrdType.Market:
                return(OrderType.Market);

            case OrdType.Limit:
                return(OrderType.Limit);

            case OrdType.Stop:
                return(OrderType.Stop);

            case OrdType.StopLimit:
                return(OrderType.StopLimit);

            case OrdType.MarketOnClose:
                return(OrderType.MarketOnClose);

            default:
                switch (type)
                {
                case OrdType.TrailingStop:
                    return(OrderType.Trail);

                case OrdType.TrailingStopLimit:
                    return(OrderType.TrailLimit);

                default:
                    throw new ArgumentException(string.Format("OrdType is not supported - {0}", type));
                }
                break;
            }
        }
Exemplo n.º 4
0
        //35 = D
        public override void onMessage(QuickFix42.NewOrderSingle message, SessionID sessionID)
        {
            Console.WriteLine("Receive message " + message.getHeader().getField(35) + ", session: " + sessionID.toString());
            try
            {
                ClOrdID      clordid = message.getClOrdID();
                string       clord   = clordid.getValue();
                Side         side    = message.getSide();
                char         s       = side.getValue();
                OrdType      ordtype = message.getOrdType();
                char         ord     = ordtype.getValue();
                TransactTime time    = message.getTransactTime();
                DateTime     dt      = time.getValue();

                QuickFix42.ExecutionReport executionReport = new QuickFix42.ExecutionReport(new OrderID("neworderid"), new ExecID("Hehe")
                                                                                            , new ExecTransType(ExecTransType.CORRECT), new ExecType(ExecType.NEW), new OrdStatus(OrdStatus.DONE_FOR_DAY),
                                                                                            new Symbol("VND"), new Side(Side.BUY), new LeavesQty(1), new CumQty(2), new AvgPx(100));

                bool x = Session.sendToTarget(executionReport, sessionID);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Exemplo n.º 5
0
        public void NewOrder(string clrID, char handinst, char sideID, char orderType, string symbolID, string exchange, float?price, long Quantity)
        {
            ClOrdID      clOrdID = new ClOrdID(clrID);
            HandlInst    inst    = new HandlInst('1');//似乎国信只支持直通私有
            Side         side    = new Side(sideID);
            OrdType      ordType = new OrdType(orderType);
            Symbol       symbol  = new Symbol(symbolID);
            TransactTime time    = new TransactTime();

            QuickFix42.NewOrderSingle message = new QuickFix42.NewOrderSingle(clOrdID, inst, symbol, side, time, ordType);
            message.setString(38, Quantity.ToString());
            if (ordType.getValue() == OrdType.LIMIT)
            {
                message.setString(44, price.Value.ToString());
            }
            message.setString(15, "CNY");
            if (exchange == "SH")
            {
                message.setString(207, "XSHG");
            }
            else if (exchange == "SZ")
            {
                message.setString(207, "XSHE");
            }
            SendToServer(message);
        }
Exemplo n.º 6
0
        private void MakeOrder(Side side, OrdType ordType)
        {
            Instrument instrument = (this.dgvQuotes.SelectedRows[0] as QuoteViewRow).Instrument;
            byte       route      = (byte)0;

            if (this.executionProvider is IMultiRouteExecutionProvider)
            {
                route = this.SelectedRoute;
            }
            OrderMiniBlotterForm orderMiniBlotterForm = new OrderMiniBlotterForm();

            orderMiniBlotterForm.Init(instrument, ordType, side, route);
            if (orderMiniBlotterForm.ShowDialog((IWin32Window)this) == DialogResult.OK)
            {
                SingleOrder singleOrder = null;
                switch (ordType)
                {
                case OrdType.Market:
                    singleOrder = new MarketOrder(this.executionProvider, this.portfolio, instrument, side, (double)orderMiniBlotterForm.Qty);
                    break;

                case OrdType.Limit:
                    singleOrder = new LimitOrder(this.executionProvider, this.portfolio, instrument, side, (double)orderMiniBlotterForm.Qty, orderMiniBlotterForm.LimitPrice);
                    break;

                case OrdType.Stop:
                    singleOrder = new StopOrder(this.executionProvider, this.portfolio, instrument, side, (double)orderMiniBlotterForm.Qty, orderMiniBlotterForm.StopPrice);
                    break;

                case OrdType.StopLimit:
                    singleOrder = new StopLimitOrder(this.executionProvider, this.portfolio, instrument, side, (double)orderMiniBlotterForm.Qty, orderMiniBlotterForm.LimitPrice, orderMiniBlotterForm.StopPrice);
                    break;
                }
                ((NewOrderSingle)singleOrder).TimeInForce = orderMiniBlotterForm.TimeInForce;
                ((FIXNewOrderSingle)singleOrder).Route    = (int)orderMiniBlotterForm.Route;
                singleOrder.Persistent = this.portfolio.Persistent;
                if (!((IProvider)this.executionProvider).IsConnected)
                {
                    bool flag = false;
                    if (MessageBox.Show(this, "Cannot send the order, because provider is not connected." + Environment.NewLine + "Do you want to connect to " + ((IProvider)this.executionProvider).Name + "?", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                    {
                        flag = true;
                        ((IProvider)this.executionProvider).Connect(15000);
                    }
                    if (flag && !((IProvider)this.marketDataProvider).IsConnected)
                    {
                        MessageBox.Show(this, "Unable to connect to " + this.marketDataProvider.Name, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                }
                if (((IProvider)this.executionProvider).IsConnected)
                {
                    singleOrder.Send();
                }
                if ((int)orderMiniBlotterForm.Route > 0)
                {
                    this.SelectedRoute = orderMiniBlotterForm.Route;
                }
            }
            orderMiniBlotterForm.Dispose();
        }
Exemplo n.º 7
0
        public void OnMessage(QuickFix.FIX43.NewOrderSingle n, SessionID s)
        {
            Symbol   symbol   = n.Symbol;
            Side     side     = n.Side;
            OrdType  ordType  = n.OrdType;
            OrderQty orderQty = n.OrderQty;
            Price    price    = new Price(DEFAULT_MARKET_PRICE);
            ClOrdID  clOrdID  = n.ClOrdID;

            switch (ordType.getValue())
            {
            case OrdType.LIMIT:
                price = n.Price;
                if (price.Obj == 0)
                {
                    throw new IncorrectTagValue(price.Tag);
                }
                break;

            case OrdType.MARKET: break;

            default: throw new IncorrectTagValue(ordType.Tag);
            }

            QuickFix.FIX43.ExecutionReport exReport = new QuickFix.FIX43.ExecutionReport(
                new OrderID(GenOrderID()),
                new ExecID(GenExecID()),
                new ExecType(ExecType.FILL),
                new OrdStatus(OrdStatus.FILLED),
                symbol, // Shouldn't be here?
                side,
                new LeavesQty(0),
                new CumQty(orderQty.getValue()),
                new AvgPx(price.getValue()));

            exReport.Set(clOrdID);
            exReport.Set(symbol);
            exReport.Set(orderQty);
            exReport.Set(new LastQty(orderQty.getValue()));
            exReport.Set(new LastPx(price.getValue()));

            if (n.IsSetAccount())
            {
                exReport.SetField(n.Account);
            }

            try
            {
                Session.SendToTarget(exReport, s);
            }
            catch (SessionNotFound ex)
            {
                Console.WriteLine("==session not found exception!==");
                Console.WriteLine(ex.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseOrder" /> class.
        /// </summary>
        /// <param name="clOrdId">Reference field provided by client. Cannot exceed 20 characters, only alphanumeric characters are allowed. (required).</param>
        /// <param name="ordType">ordType (required).</param>
        /// <param name="symbol">Blockchain symbol identifier (required).</param>
        /// <param name="side">side (required).</param>
        /// <param name="orderQty">The order size in the terms of the base currency (required).</param>
        /// <param name="timeInForce">timeInForce.</param>
        /// <param name="price">The limit price for the order.</param>
        /// <param name="expireDate">expiry date in the format YYYYMMDD.</param>
        /// <param name="minQty">The minimum quantity required for an IOC fill.</param>
        /// <param name="stopPx">The limit price for the order.</param>
        public BaseOrder(string clOrdId = default(string), OrdType ordType = default(OrdType), string symbol = default(string), Side side = default(Side), double orderQty = default(double), TimeInForce?timeInForce = default(TimeInForce?), double price = default(double), int expireDate = default(int), double minQty = default(double), double stopPx = default(double))
        {
            // to ensure "clOrdId" is required (not null)
            if (clOrdId == null)
            {
                throw new InvalidDataException("clOrdId is a required property for BaseOrder and cannot be null");
            }
            else
            {
                this.ClOrdId = clOrdId;
            }

            // to ensure "ordType" is required (not null)
            if (ordType == null)
            {
                throw new InvalidDataException("ordType is a required property for BaseOrder and cannot be null");
            }
            else
            {
                this.OrdType = ordType;
            }

            // to ensure "symbol" is required (not null)
            if (symbol == null)
            {
                throw new InvalidDataException("symbol is a required property for BaseOrder and cannot be null");
            }
            else
            {
                this.Symbol = symbol;
            }

            // to ensure "side" is required (not null)
            if (side == null)
            {
                throw new InvalidDataException("side is a required property for BaseOrder and cannot be null");
            }
            else
            {
                this.Side = side;
            }

            // to ensure "orderQty" is required (not null)
            if (orderQty == null)
            {
                throw new InvalidDataException("orderQty is a required property for BaseOrder and cannot be null");
            }
            else
            {
                this.OrderQty = orderQty;
            }

            this.TimeInForce = timeInForce;
            this.Price       = price;
            this.ExpireDate  = expireDate;
            this.MinQty      = minQty;
            this.StopPx      = stopPx;
        }
Exemplo n.º 9
0
 public OrderDetailsWrapper LimitOrder(Side side, double price, int qty, Route route = null, string symbol = "IWM")
 {
     OrderType = OrdType.Limit;
     OrderHelper(side, price, qty, symbol);
     if (route != null)
     {
         Route = route;
     }
     return(this);
 }
Exemplo n.º 10
0
 public OrderDetailsWrapper MarketOrder(Side side, int qty, Route route = null, string symbol = "IWM")
 {
     OrderType = OrdType.Market;
     OrderHelper(side, 0.00, qty, symbol);
     if (route != null)
     {
         Route = route;
     }
     return(this);
 }
Exemplo n.º 11
0
        public static OrderType Convert(OrdType type)
        {
            switch (type.getValue())
            {
            case OrdType.LIMIT:
                return(OrderType.Limit);

            default:
                throw new IncorrectTagValue(type.Tag);
            }
        }
Exemplo n.º 12
0
        private static void ValidateIsSupportedOrderType(OrdType ordType)
        {
            switch (ordType.getValue())
            {
            case OrdType.LIMIT:
                break;

            default:
                throw new IncorrectTagValue(ordType.Tag);
            }
        }
Exemplo n.º 13
0
        public Message NewOrder(MDEntryGroup entryGroup, double quantity)
        {
            bool isInvertedSecurity = entryGroup.OwnerEntry.IsInverted;
            Message message = null;
            Account account = new Account(GetOrderSession().getSenderCompID().ToLower());

            ClOrdID clOrdId = new ClOrdID("ClOrd_" + Guid.NewGuid());
            HandlInst handlInst = new HandlInst(HandlInst.AUTOMATED_EXECUTION_ORDER_PRIVATE_NO_BROKER_INTERVENTION);
            OrdType ordType = new OrdType(OrdType.LIMIT);
            TimeInForce timeInForce = new TimeInForce(TimeInForce.FILL_OR_KILL);
            TransactTime transactTime = new TransactTime();

            Price price = new Price(entryGroup.MDEntryPx);
            SecurityExchange securityExchange = new SecurityExchange(entryGroup.OwnerEntry.SecurityExchange);
            SecurityType securityType = new SecurityType(entryGroup.OwnerEntry.SecurityType);
            Symbol symbol = new Symbol(entryGroup.OwnerEntry.Symbol);
            SecurityID securityId = new SecurityID(entryGroup.OwnerEntry.SecurityID);
            OrderQty orderQty = new OrderQty(quantity);

            Side side = null;
            switch (entryGroup.MDEntryType)
            {
                case MDEntryType.BID:
                    side = new Side(Side.SELL);
                    break;
                case MDEntryType.OFFER:
                    side = new Side(Side.BUY);
                    break;
                default:
                    throw new Exception("Undefined entry type.");
            }

            //if (isInvertedSecurity && side.getValue() == Side.BUY)
            //    price = new Price(-price.getValue());

            message = new QuickFix42.NewOrderSingle();

            ((QuickFix42.NewOrderSingle) message).set(account);

            ((QuickFix42.NewOrderSingle) message).set(clOrdId);
            ((QuickFix42.NewOrderSingle) message).set(side);
            ((QuickFix42.NewOrderSingle) message).set(transactTime);
            ((QuickFix42.NewOrderSingle) message).set(ordType);

            ((QuickFix42.NewOrderSingle) message).set(price);
            ((QuickFix42.NewOrderSingle) message).set(orderQty);
            ((QuickFix42.NewOrderSingle) message).set(securityId);
            ((QuickFix42.NewOrderSingle) message).set(securityExchange);
            ((QuickFix42.NewOrderSingle) message).set(timeInForce);

            ((QuickFix42.NewOrderSingle) message).set(securityType);

            return message;
        }
Exemplo n.º 14
0
        public void OnMessage(QuickFix.FIX44.NewOrderSingle n, SessionID s)
        {
            Symbol   symbol   = n.Symbol;
            Side     side     = n.Side;
            OrdType  ordType  = n.OrdType;
            OrderQty orderQty = n.OrderQty;
            Price    price    = n.Price;
            ClOrdID  clOrdID  = n.ClOrdID;

            if (ordType.getValue() != OrdType.LIMIT)
            {
                throw new IncorrectTagValue(ordType.Tag);
            }

            QuickFix.FIX44.ExecutionReport exReport = new QuickFix.FIX44.ExecutionReport(
                new OrderID(GenOrderID()),
                new ExecID(GenExecID()),
                new ExecType(ExecType.FILL),
                new OrdStatus(OrdStatus.FILLED),
                symbol, //shouldn't be here?
                side,
                new LeavesQty(0),
                new CumQty(orderQty.getValue()),
                new AvgPx(price.getValue()));

            exReport.Set(clOrdID);
            exReport.Set(symbol);
            exReport.Set(orderQty);
            exReport.Set(new LastQty(orderQty.getValue()));
            exReport.Set(new LastPx(price.getValue()));

            if (n.IsSetAccount())
            {
                exReport.SetField(n.Account);
            }

            try
            {
                Session.SendToTarget(exReport, s);
            }
            catch (SessionNotFound ex)
            {
                Console.WriteLine("==session not found exception!==");
                Console.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("==unknown exception==");
                Console.WriteLine(ex.ToString());
                Console.WriteLine(ex.StackTrace);
            }
        }
Exemplo n.º 15
0
 public OrderMessage(string price, string operation, OrdType ordType)
 {
     ClOrdID      = NewRandom.Rnd.Next(99999999).ToString();
     Side         = operation;
     TransactTime = DateTime.Now.AddHours(-3).ToString("yyyyMMdd-HH:mm:ss.fff");
     OrdType      = (int)ordType;
     Price        = price;
     OrderQty     = 10;
     HandlInst    = '2';
     IDSource     = "8";     //  100
     Symbol       = "SBER";  //  SBER    ISIN RU0009029540   Сбербанк    RTS-3.20    RIH0
     Account      = "L01+00000F00";
     ClientID     = "1234";  //  1234 SPBFUT00086
 }
Exemplo n.º 16
0
        public override void onMessage(QuickFix42.NewOrderSingle order, SessionID sessionID)
        {
            Symbol   symbol   = new Symbol();
            Side     side     = new Side();
            OrdType  ordType  = new OrdType();
            OrderQty orderQty = new OrderQty();
            Price    price    = new Price();
            ClOrdID  clOrdID  = new ClOrdID();

            order.get(ordType);

            if (ordType.getValue() != OrdType.LIMIT)
            {
                throw new IncorrectTagValue(ordType.getField());
            }

            order.get(symbol);
            order.get(side);
            order.get(orderQty);
            order.get(price);
            order.get(clOrdID);

            QuickFix42.ExecutionReport executionReport = new QuickFix42.ExecutionReport
                                                             (genOrderID(),
                                                             genExecID(),
                                                             new ExecTransType(ExecTransType.NEW),
                                                             new ExecType(ExecType.FILL),
                                                             new OrdStatus(OrdStatus.FILLED),
                                                             symbol,
                                                             side,
                                                             new LeavesQty(0),
                                                             new CumQty(orderQty.getValue()),
                                                             new AvgPx(price.getValue()));

            executionReport.set(clOrdID);
            executionReport.set(orderQty);
            executionReport.set(new LastShares(orderQty.getValue()));
            executionReport.set(new LastPx(price.getValue()));

            if (order.isSetAccount())
            {
                executionReport.set(order.getAccount());
            }

            try
            {
                Session.sendToTarget(executionReport, sessionID);
            }
            catch (SessionNotFound) {}
        }
        private OrderType ConvertOrderType(OrdType orderType)
        {
            switch (orderType.Obj)
            {
            case OrdType.MARKET:
                return(OrderType.Market);

            case OrdType.LIMIT:
                return(OrderType.Limit);

            default:
                return(OrderType.Unknown);
            }
        }
Exemplo n.º 18
0
        public void Order(string price, string operation, OrdType ordType)
        {
            HeaderMessage msHeader = new HeaderMessage(ApplicationLevel.NewOrderSingle, _messageCount++);

            OrderMessage msOrder = new OrderMessage(price, operation, ordType);

            TrailerMessage msTrailer = new TrailerMessage(msHeader.ToString() + msOrder.ToString());

            msHeader.BodyLength = msHeader.MessageSize + msOrder.MessageSize;  //  GetMessageSize()

            //Формируем полное готовое сообщение
            string fullMessage = msHeader.MessageString + msOrder.MessageString + msTrailer.ToString();   // ToString()

            SendMessage(fullMessage);
        }
Exemplo n.º 19
0
        public void OnMessage(QuickFix.FIX44.NewOrderSingle n, SessionID s)
        {
            Symbol   symbol   = n.Symbol;
            Side     side     = n.Side;
            OrdType  ordType  = n.OrdType;
            OrderQty orderQty = n.OrderQty;
            Price    price    = new Price(DEFAULT_MARKET_PRICE);
            ClOrdID  clOrdID  = n.ClOrdID;

            switch (ordType.getValue())
            {
            case OrdType.LIMIT:
                price = n.Price;
                if (price.Obj == 0)
                {
                    throw new IncorrectTagValue(price.Tag);
                }
                break;

            case OrdType.MARKET: break;

            default: throw new IncorrectTagValue(ordType.Tag);
            }

            // Send Status New
            SendExecution(s, OrdStatus.NEW, ExecType.NEW, n, n.OrderQty.getValue(), 0, 0, 0, 0);
            Thread.Sleep(1000);

            // Send Status Partially Filled
            decimal filledQty = Math.Abs(Math.Round(n.OrderQty.getValue() / 4, 2));
            decimal cumQty    = filledQty;

            SendExecution(s, OrdStatus.PARTIALLY_FILLED, ExecType.PARTIAL_FILL, n, filledQty, filledQty, price.getValue(), filledQty, price.getValue());
            Thread.Sleep(1000);

            // Send Status Partially Filled
            filledQty = Math.Abs(Math.Round(n.OrderQty.getValue() / 4, 2));
            cumQty   += filledQty;
            SendExecution(s, OrdStatus.PARTIALLY_FILLED, ExecType.PARTIAL_FILL, n, n.OrderQty.getValue() - cumQty, cumQty, price.getValue(), filledQty, price.getValue());
            Thread.Sleep(1000);

            // Send Status Fully Filled
            filledQty = n.OrderQty.getValue() - cumQty;
            cumQty   += filledQty;
            SendExecution(s, OrdStatus.FILLED, ExecType.FILL, n, 0, cumQty, price.getValue(), filledQty, price.getValue());
        }
Exemplo n.º 20
0
  public override void onMessage( QuickFix41.NewOrderSingle order, SessionID sessionID )
  {
    Symbol symbol = new Symbol();
    Side side = new Side();
    OrdType ordType = new OrdType();
    OrderQty orderQty = new OrderQty();
    Price price = new Price();
    ClOrdID clOrdID = new ClOrdID();

    order.get( ordType );

    if ( ordType.getValue() != OrdType.LIMIT )
      throw new IncorrectTagValue( ordType.getField() );
    
    order.get( symbol );
    order.get( side );
    order.get( orderQty );
    order.get( price );
    order.get( clOrdID );

    QuickFix41.ExecutionReport executionReport = new QuickFix41.ExecutionReport
        ( genOrderID(),
          genExecID(),
          new ExecTransType( ExecTransType.NEW ),
          new ExecType( ExecType.FILL ),
          new OrdStatus ( OrdStatus.FILLED ),
          symbol,
          side,
          orderQty,
          new LastShares ( orderQty.getValue() ),
          new LastPx ( price.getValue() ),
          new LeavesQty( 0 ),
          new CumQty ( orderQty.getValue() ),
          new AvgPx ( price.getValue() ) );

    executionReport.set( clOrdID );

    if( order.isSetAccount() )
      executionReport.set( order.getAccount() );

    try
    {
      Session.sendToTarget( executionReport, sessionID );
    }
    catch ( SessionNotFound ) {}
  }
Exemplo n.º 21
0
        public void OnMessage(QuickFix.FIX44.NewOrderSingle ord, SessionID sessionID)
        {
            Symbol   symbol   = ord.Symbol;
            Side     side     = ord.Side;
            OrdType  ordType  = ord.OrdType;
            OrderQty orderQty = ord.OrderQty;
            Price    price    = new Price(10);
            //q isso?
            ClOrdID clOrdID = ord.ClOrdID;

            QuickFix.FIX44.ExecutionReport exReport = new QuickFix.FIX44.ExecutionReport(
                new OrderID(GenOrderID()),
                new ExecID(GenExecID()),
                new ExecType(ExecType.FILL),
                new OrdStatus(OrdStatus.FILLED),
                symbol,
                side,
                new LeavesQty(0),
                new CumQty(orderQty.getValue()),
                new AvgPx(price.getValue())
                );
            exReport.ClOrdID  = clOrdID;
            exReport.Symbol   = symbol;
            exReport.OrderQty = orderQty;
            exReport.LastQty  = new LastQty(orderQty.getValue());
            exReport.LastPx   = new LastPx(price.getValue());

            if (ord.IsSetAccount())
            {
                exReport.Account = ord.Account;
            }
            try
            {
                Session.SendToTarget(exReport, sessionID);
            }
            catch (SessionNotFound ex)
            {
                Console.WriteLine("==session not found exception!==");
                Console.WriteLine(ex.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Exemplo n.º 22
0
        private static Order Convert(MessageType commandType,
                                     Symbol symbol,
                                     Side side,
                                     OrdType ordType,
                                     OrderQty orderQty,
                                     Price price,
                                     ClOrdID clOrdId,
                                     Account account)
        {
            switch (ordType.getValue())
            {
            case OrdType.LIMIT:
                if (price.Obj == 0)
                {
                    throw new IncorrectTagValue(price.Tag);
                }

                break;

            //case OrdType.MARKET: break;

            default:
                throw new IncorrectTagValue(ordType.Tag);
            }
            var orderId = DIContainer.ResolveByName <IdGenerator>("OrderIdGenerator").GenerateId();

            return(new Order
            {
                CommandType = commandType,
                OrderId = orderId,
                OrderSide = FixFieldsConverter.Convert(side),
                Asset = new Asset(symbol.getValue()),
                OrderType = FixFieldsConverter.Convert(ordType),
                Quantity = orderQty.getValue(),
                Price = price.getValue(),
                ClOrdId = clOrdId.getValue(),
                Account =
                    account == null
                            ? TradingAccount.None
                            : new TradingAccount(account.getValue())
            });
        }
Exemplo n.º 23
0
        public static void Add(QuickFix42.Message msg)
        {
            ClOrdID clientId  = new ClOrdID();
            OrdType orderType = new OrdType();

            msg.getField(clientId);


            Msgs.Add(clientId.getValue(), msg);


            if (msg.isSetField(orderType))
            {
                msg.getField(orderType);
                if (orderType.getValue() == OrdType.LIMIT)
                {
                    LimitOrders.Add(clientId.getValue());
                    LimitLib.Add(clientId.getValue());
                }
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Returns the string presentation of the object
        /// </summary>
        /// <returns>String presentation of the object</returns>
        public override string ToString()
        {
            var sb = new System.Text.StringBuilder();

            sb.Append("class OrderResponse {\n");
            sb.Append("  OrderID: ").Append(OrderId.ToString()).Append("\n");
            sb.Append("  ClOrdID: ").Append(ClOrdId.ToString()).Append("\n");
            sb.Append("  ClOrdLinkID: ").Append(ClOrdLinkId.ToString()).Append("\n");
            sb.Append("  Account: ").Append(Account.ToString()).Append("\n");
            sb.Append("  Symbol: ").Append(Symbol.ToString()).Append("\n");
            sb.Append("  Side: ").Append(Side.ToString()).Append("\n");
            sb.Append("  OrderQty: ").Append(OrderQty.ToString()).Append("\n");
            sb.Append("  Price: ").Append(Price.ToString()).Append("\n");
            sb.Append("  DisplayQty: ").Append((DisplayQty == null) ? "null" : DisplayQty.ToString()).Append("\n");
            sb.Append("  StopPx: ").Append((StopPx == null) ? "null" : StopPx.ToString()).Append("\n");
            sb.Append("  PegOffsetValue: ").Append((PegOffsetValue == null) ? "null" : PegOffsetValue.ToString()).Append("\n");
            sb.Append("  PegPriceType: ").Append((PegPriceType == null) ? "null" : PegPriceType.ToString()).Append("\n");
            sb.Append("  Currency: ").Append((Currency == null) ? "null" : Currency.ToString()).Append("\n");
            sb.Append("  SettlCurrency: ").Append((SettlCurrency == null) ? "null" : SettlCurrency.ToString()).Append("\n");
            sb.Append("  OrdType: ").Append((OrdType == null) ? "null" : OrdType.ToString()).Append("\n");
            sb.Append("  TimeInForce: ").Append((TimeInForce == null) ? "null" : TimeInForce.ToString()).Append("\n");
            sb.Append("  ExecInst: ").Append((ExecInst == null) ? "null" : ExecInst.ToString()).Append("\n");
            sb.Append("  ContingencyType: ").Append((ContingencyType == null) ? "null" : ContingencyType.ToString()).Append("\n");
            sb.Append("  ExDestination: ").Append((ExDestination == null) ? "null" : ExDestination.ToString()).Append("\n");
            sb.Append("  OrdStatus: ").Append((OrdStatus == null) ? "null" : OrdStatus.ToString()).Append("\n");
            sb.Append("  Triggered: ").Append((Triggered == null) ? "null" : Triggered.ToString()).Append("\n");
            sb.Append("  WorkingIndicator: ").Append((WorkingIndicator == null) ? "null" : WorkingIndicator.ToString()).Append("\n");
            sb.Append("  OrdRejReason: ").Append((OrdRejReason == null) ? "null" : OrdRejReason.ToString()).Append("\n");
            sb.Append("  LeavesQty: ").Append((LeavesQty == null) ? "null" : LeavesQty.ToString()).Append("\n");
            sb.Append("  CumQty: ").Append((CumQty == null) ? "null" : CumQty.ToString()).Append("\n");
            sb.Append("  AvgPx: ").Append((AvgPx == null) ? "null" : AvgPx.ToString()).Append("\n");
            sb.Append("  MultiLegReportingType: ").Append((MultiLegReportingType == null) ? "null" : MultiLegReportingType.ToString()).Append("\n");
            sb.Append("  Text: ").Append((Text == null) ? "null" : Text.ToString()).Append("\n");
            sb.Append("  TransactTime: ").Append(TransactTime.ToString()).Append("\n");
            sb.Append("  Timestamp: ").Append(Timestamp.ToString()).Append("\n");
            sb.Append("}\n");
            return(sb.ToString());
        }
Exemplo n.º 25
0
        private static OrderData TranslateOrderImpl(Symbol symbol,
                                                    Side side,
                                                    OrdType ordType,
                                                    OrderQty orderQty,
                                                    Price price,
                                                    ClOrdID clOrdID,
                                                    Account account)
        {
            switch (ordType.getValue())
            {
            case OrdType.LIMIT:
                if (price.Obj == 0)
                {
                    throw new IncorrectTagValue(price.Tag);
                }

                break;

            //case OrdType.MARKET: break;

            default:
                throw new IncorrectTagValue(ordType.Tag);
            }

            return(new OrderData
            {
                MarketSide = TranslateFixFields.Translate(side),
                Symbol = symbol.getValue(),
                OrderType = TranslateFixFields.Translate(ordType),
                Quantity = orderQty.getValue(),
                Price = price.getValue(),
                ClOrdID = clOrdID.getValue(),
                Account =
                    account == null
                            ? TradingAccount.None
                            : new TradingAccount(account.getValue())
            });
        }
Exemplo n.º 26
0
        private Queue <QuickFix.FIX42.NewOrderSingle> CreateOrders(int n)
        {
            Queue <QuickFix.FIX42.NewOrderSingle> orders = new Queue <QuickFix.FIX42.NewOrderSingle>(n);

            for (int i = 0; i < n; i++)
            {
                ClOrdID      cloudOrderId           = new ClOrdID(Guid.NewGuid().ToString());
                HandlInst    handlInst              = new HandlInst(HandlInst.AUTOMATED_EXECUTION_ORDER_PRIVATE_NO_BROKER_INTERVENTION);
                Symbol       symbol                 = new Symbol("MSFT");
                Side         side                   = new Side(Side.BUY);
                TransactTime time                   = new TransactTime();
                OrdType      orderType              = new OrdType(OrdType.LIMIT);
                QuickFix.FIX42.NewOrderSingle order = new QuickFix.FIX42.NewOrderSingle(cloudOrderId, handlInst, symbol, side, time, orderType);
                order.Account       = new Account("Account");
                order.OrderQty      = new OrderQty(100);
                order.ExDestination = new ExDestination("*");
                order.TimeInForce   = new TimeInForce(TimeInForce.DAY);
                order.Price         = new Price(50m);
                order.SecurityType  = new SecurityType(SecurityType.COMMON_STOCK);
                orders.Enqueue(order);
            }
            return(orders);
        }
Exemplo n.º 27
0
        public int amendOrder(ref OrderStruct os)
        {
            if (!isOrderAmendPossible(os.OrderStatus))
            {
                return(-1);
            }
            OrderDAO ord      = new OrderDAO();
            int      newOrdID = ord.amendOrder(ref os); // OrderID is the last FixAccepted version

            Console.WriteLine("TODO: Send FIX - cancel for os.LinkedOrderID ; Send FIX - New for os.ID");
            OrigClOrdID origCLOrdID = new OrigClOrdID(Convert.ToString(os.ID));
            ClOrdID     OrdId       = new ClOrdID(Convert.ToString(newOrdID));
            string      symboldata  = sanitiseField(os.symbol);
            Symbol      symbol      = new Symbol(symboldata);
            Side        side        = new Side(Side.BUY);

            if (os.direction == 'S')
            {
                side = new Side(Side.SELL);
            }
            OrdType ordType = new OrdType(OrdType.LIMIT);

            if (os.orderType == 1)
            {
                ordType = new OrdType(OrdType.MARKET);
            }
            var orderMod = new QuickFix.FIX42.OrderCancelReplaceRequest(origCLOrdID, OrdId, new HandlInst('1'), symbol, side, new TransactTime(DateTime.Now.ToUniversalTime()), ordType);
            int Qty      = (int)os.quantity;

            orderMod.Price = new Price((decimal)os.price);
            orderMod.SetField(new OrderQty(Qty));
            Console.WriteLine("Modifying origOrdId/FixAcceptedID : " + os.ID + " newOrderID : " + newOrdID);
            Console.WriteLine("symboldata : " + symboldata + " side : " + side + " Price : " + os.price + " qty : " + os.quantity);
            Session.SendToTarget(orderMod, FixClient.MySess);
            return(os.OrderNo);
        }
        private void SendExecReport(NewOrderSingle newOrderSingle, IExecutionEngineSettings settings)
        {
            OrdType ordType = newOrderSingle.OrdType;
            Price   price   = new Price(10);

            switch (ordType.getValue())
            {
            case OrdType.LIMIT:
                price = newOrderSingle.Price;
                if (price.Obj == 0)
                {
                    throw new IncorrectTagValue(price.Tag);
                }
                break;

            case OrdType.MARKET:
                break;

            default:
                throw new IncorrectTagValue(ordType.Tag);
            }

            OrderQty orderQty = newOrderSingle.OrderQty;
            var      exReport = new QuickFix.FIX42.ExecutionReport();

            exReport.CopyFromOrder(newOrderSingle);
            exReport.Set(new ExecTransType(ExecTransType.NEW));
            exReport.Set(new ExecType(ExecType.FILL));
            exReport.Set(new LastPx(price.getValue()));
            exReport.Set(new AvgPx(price.getValue()));

            decimal qtyPerSlice = orderQty.getValue() *
                                  ((settings.EachFillPercentange ?? 100) / 100m);

            decimal leaves = orderQty.getValue();
            decimal cumQty = 0;

            while (leaves != 0)
            {
                if (leaves <= qtyPerSlice)
                {
                    leaves      = 0;
                    qtyPerSlice = leaves;
                    exReport.Set(new OrdStatus(OrdStatus.FILLED));
                }
                else
                {
                    leaves -= qtyPerSlice;
                    exReport.Set(new OrdStatus(OrdStatus.PARTIALLY_FILLED));
                }

                cumQty += qtyPerSlice;
                exReport.Set(new OrderID(GenOrderID()));
                exReport.Set(new ExecID(GenExecID()));

                exReport.Set(new LeavesQty(leaves));
                exReport.Set(new CumQty(cumQty));

                exReport.Set(new LastShares(qtyPerSlice));
                SendExecReport(exReport);
                Thread.Sleep(Convert.ToInt32(settings.SecondsBetweenFills * 1000));
            }
        }
Exemplo n.º 29
0
 private void MakeOrder(Side side, OrdType ordType)
 {
     Instrument instrument = (this.dgvQuotes.SelectedRows[0] as QuoteViewRow).Instrument;
     byte route = (byte)0;
     if (this.executionProvider is IMultiRouteExecutionProvider)
         route = this.SelectedRoute;
     OrderMiniBlotterForm orderMiniBlotterForm = new OrderMiniBlotterForm();
     orderMiniBlotterForm.Init(instrument, ordType, side, route);
     if (orderMiniBlotterForm.ShowDialog((IWin32Window)this) == DialogResult.OK)
     {
         SingleOrder singleOrder = null;
         switch (ordType)
         {
             case OrdType.Market:
                 singleOrder = new MarketOrder(this.executionProvider, this.portfolio, instrument, side, (double)orderMiniBlotterForm.Qty);
                 break;
             case OrdType.Limit:
                 singleOrder = new LimitOrder(this.executionProvider, this.portfolio, instrument, side, (double)orderMiniBlotterForm.Qty, orderMiniBlotterForm.LimitPrice);
                 break;
             case OrdType.Stop:
                 singleOrder = new StopOrder(this.executionProvider, this.portfolio, instrument, side, (double)orderMiniBlotterForm.Qty, orderMiniBlotterForm.StopPrice);
                 break;
             case OrdType.StopLimit:
                 singleOrder = new StopLimitOrder(this.executionProvider, this.portfolio, instrument, side, (double)orderMiniBlotterForm.Qty, orderMiniBlotterForm.LimitPrice, orderMiniBlotterForm.StopPrice);
                 break;
         }
         ((NewOrderSingle)singleOrder).TimeInForce = orderMiniBlotterForm.TimeInForce;
         ((FIXNewOrderSingle)singleOrder).Route = (int)orderMiniBlotterForm.Route;
         singleOrder.Persistent = this.portfolio.Persistent;
         if (!((IProvider)this.executionProvider).IsConnected)
         {
             bool flag = false;
             if (MessageBox.Show(this, "Cannot send the order, because provider is not connected." + Environment.NewLine + "Do you want to connect to " + ((IProvider)this.executionProvider).Name + "?", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
             {
                 flag = true;
                 ((IProvider)this.executionProvider).Connect(15000);
             }
             if (flag && !((IProvider)this.marketDataProvider).IsConnected)
             {
                 MessageBox.Show(this, "Unable to connect to " + this.marketDataProvider.Name, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
             }
         }
         if (((IProvider)this.executionProvider).IsConnected)
             singleOrder.Send();
         if ((int)orderMiniBlotterForm.Route > 0)
             this.SelectedRoute = orderMiniBlotterForm.Route;
     }
     orderMiniBlotterForm.Dispose();
 }
Exemplo n.º 30
0
 public void Init(Instrument instrument, OrdType ordType, Side side, byte route)
 {
     this.Text = string.Format("{0} - {1} {2}", instrument, side, ordType);
     int decimalPlaces = PriceFormatHelper.GetDecimalPlaces(instrument);
     Decimal num1 = (Decimal)Math.Pow(0.1, (double)decimalPlaces);
     this.nudLimitPrice.DecimalPlaces = decimalPlaces;
     this.nudStopPrice.DecimalPlaces = decimalPlaces;
     this.nudLimitPrice.Increment = num1;
     this.nudStopPrice.Increment = num1;
     this.nudLimitPrice.Enabled = false;
     this.nudStopPrice.Enabled = false;
     switch (ordType)
     {
         case OrdType.Market:
             switch (side)
             {
                 case Side.Buy:
                     this.nudLimitPrice.Value = (Decimal)instrument.Quote.Ask;
                     this.nudStopPrice.Value = (Decimal)instrument.Quote.Ask;
                     break;
                 case Side.Sell:
                     this.nudLimitPrice.Value = (Decimal)instrument.Quote.Bid;
                     this.nudStopPrice.Value = (Decimal)instrument.Quote.Bid;
                     break;
                 default:
                     throw new NotSupportedException("Not supported order side - " + ((object)side).ToString());
             }
             this.cbxTIFs.BeginUpdate();
             this.cbxTIFs.Items.Clear();
             foreach (OpenQuant.API.TimeInForce timeInForce in Enum.GetValues(typeof (OpenQuant.API.TimeInForce)))
                 this.cbxTIFs.Items.Add((object)timeInForce);
             this.cbxTIFs.SelectedItem = (object)OpenQuant.API.TimeInForce.Day;
             this.cbxTIFs.EndUpdate();
             if ((int)route > 0)
             {
                 OrderMiniBlotterForm orderMiniBlotterForm = this;
                 int num2 = orderMiniBlotterForm.Height + 32;
                 orderMiniBlotterForm.Height = num2;
                 Button button1 = this.btnSend;
                 int num3 = button1.Top + 32;
                 button1.Top = num3;
                 Button button2 = this.btnCancel;
                 int num4 = button2.Top + 32;
                 button2.Top = num4;
                 GroupBox groupBox = this.groupBox1;
                 int num5 = groupBox.Height + 32;
                 groupBox.Height = num5;
                 Label label = new Label();
                 label.AutoSize = false;
                 label.TextAlign = ContentAlignment.MiddleLeft;
                 label.Location = new Point(16, 144);
                 label.Size = new Size(70, 20);
                 label.Text = "Route";
                 this.groupBox1.Controls.Add((Control)label);
                 this.cbxRoutes = new ComboBox();
                 this.cbxRoutes.DropDownStyle = ComboBoxStyle.DropDownList;
                 this.cbxRoutes.Location = new Point(104, 144);
                 this.cbxRoutes.Size = new Size(98, 21);
                 this.cbxRoutes.Sorted = true;
                 this.groupBox1.Controls.Add((Control)this.cbxRoutes);
                 this.cbxRoutes.BeginUpdate();
                 this.cbxRoutes.Items.Clear();
                 IEnumerator enumerator = ((ProviderList)ProviderManager.ExecutionProviders).GetEnumerator();
                 try
                 {
                     while (enumerator.MoveNext())
                     {
                         IExecutionProvider iexecutionProvider = (IExecutionProvider)enumerator.Current;
                         RouteItem routeItem = new RouteItem(iexecutionProvider.Name, iexecutionProvider.Id);
                         this.cbxRoutes.Items.Add((object)routeItem);
                         if ((int)((IProvider)iexecutionProvider).Id == (int)route)
                             this.cbxRoutes.SelectedItem = (object)routeItem;
                     }
                 }
                 finally
                 {
                     IDisposable disposable = enumerator as IDisposable;
                     if (disposable != null)
                         disposable.Dispose();
                 }
                 if (this.cbxRoutes.Items.Count > 0 && this.cbxRoutes.SelectedItem == null)
                     this.cbxRoutes.SelectedIndex = 0;
                 this.cbxRoutes.EndUpdate();
                 break;
             }
             else
             {
                 this.cbxRoutes = (ComboBox)null;
                 break;
             }
         case OrdType.Limit:
             this.nudLimitPrice.Enabled = true;
             goto case OrdType.Market;
         case OrdType.Stop:
             this.nudStopPrice.Enabled = true;
             goto case OrdType.Market;
         case OrdType.StopLimit:
             this.nudLimitPrice.Enabled = true;
             this.nudStopPrice.Enabled = true;
             goto case OrdType.Market;
         default:
             throw new NotSupportedException("Not supported order type - " + ordType.ToString());
     }
 }
Exemplo n.º 31
0
        public bool AlterarOrdem(OrdemInfo ordem, long ini = 0, long fim = 0, long oriini = 0, long orifim = 0, int delay = 0, string mnemonic = "", string senderSubID = "", string extraTags = "")
        {
            //Cria a mensagem FIX de NewOrderSingle
            QuickFix.FIX42.OrderCancelReplaceRequest ordercrr = new QuickFix.FIX42.OrderCancelReplaceRequest();

            ordercrr.Set(new Account(ordem.Account.ToString()));
            if (!string.IsNullOrEmpty(mnemonic))
            {
                ordercrr.SetField(new Account(mnemonic), true);
            }
            if (!string.IsNullOrEmpty(senderSubID))
            {
                ordercrr.Header.SetField(new SenderSubID(senderSubID), true);
            }
            ordercrr.Set(new Symbol(ordem.Symbol));
            ordercrr.Set(new ClOrdID(ordem.ClOrdID));
            ordercrr.Set(new OrigClOrdID(ordem.OrigClOrdID));

            if (ordem.ExchangeNumberID != null && ordem.ExchangeNumberID.Length > 0)
            {
                ordercrr.Set(new OrderID(ordem.ExchangeNumberID));
            }

            // Armazena ClOrdID em Memo (5149) para posterior referência nos tratamentos de retornos
            QuickFix.Fields.StringField field5149 = new QuickFix.Fields.StringField(5149, ordem.ClOrdID);
            ordercrr.SetField(field5149);

            //ordersingle.Set(new IDSource());
            if (ordem.Side == OrdemDirecaoEnum.Venda)
            {
                ordercrr.Set(new Side(Side.SELL));
            }
            else
            {
                ordercrr.Set(new Side(Side.BUY));
            }

            TimeInForce tif = FixMessageUtilities.deOrdemValidadeParaTimeInForce(ordem.TimeInForce);

            if (tif != null)
            {
                ordercrr.Set(tif);
            }

            ordercrr.Set(new OrderQty(ordem.OrderQty));

            if (ordem.TimeInForce == OrdemValidadeEnum.ValidoAteDeterminadaData)
            {
                DateTime expiredate = Convert.ToDateTime(ordem.ExpireDate);
                ordercrr.Set(new ExpireDate(expiredate.ToString("yyyyMMdd")));
            }

            OrdType ordType = FixMessageUtilities.deOrdemTipoParaOrdType(ordem.OrdType);

            if (ordType != null)
            {
                ordercrr.Set(ordType);
            }

            // Para versao 4.2, os novos tipos de OrdType a serem enviados (5, A ou B);
            if (!string.IsNullOrEmpty(ordem.Memo5149))
            {
                ordercrr.SetField(new OrdType(Convert.ToChar(ordem.Memo5149)), true);
            }

            // Verifica envio do preco
            switch (ordem.OrdType)
            {
            case OrdemTipoEnum.Limitada:
            case OrdemTipoEnum.MarketWithLeftOverLimit:
            case OrdemTipoEnum.StopLimitada:
                ordercrr.Set(new Price(Convert.ToDecimal(ordem.Price)));
                break;

            case OrdemTipoEnum.StopStart:
                ordercrr.Set(new Price(Convert.ToDecimal(ordem.Price)));
                ordercrr.Set(new StopPx(Convert.ToDecimal(ordem.StopPrice)));
                break;

            case OrdemTipoEnum.Mercado:
            case OrdemTipoEnum.OnClose:
                ordercrr.Set(new Price(Convert.ToDecimal(ordem.Price)));
                break;

            default:
                ordercrr.Set(new Price(Convert.ToDecimal(ordem.Price)));
                break;
            }

            ordercrr.Set(new TransactTime(DateTime.Now));
            ordercrr.Set(new HandlInst('1'));
            ordercrr.Set(new ExecBroker("227"));

            if (ordem.MaxFloor > 0)
            {
                ordercrr.Set(new MaxFloor(Convert.ToDecimal(ordem.MaxFloor)));
            }

            if (ordem.MinQty > 0)
            {
                ordercrr.Set(new MinQty(Convert.ToDecimal(ordem.MinQty)));
            }

            QuickFix.FIX42.OrderCancelReplaceRequest.NoAllocsGroup noAllocsGrp = new QuickFix.FIX42.OrderCancelReplaceRequest.NoAllocsGroup();
            noAllocsGrp.Set(new AllocAccount("67"));
            ordercrr.AddGroup(noAllocsGrp);

            bool bRet = false;

            // Tags Customizadas Bloomberg
            if (!string.IsNullOrEmpty(extraTags))
            {
                string[] arr = extraTags.Split(';');
                for (int i = 0; i < arr.Length; i++)
                {
                    if (!string.IsNullOrEmpty(arr[i]))
                    {
                        string[]    valor = arr[i].Split('=');
                        StringField fld   = new StringField(Convert.ToInt32(valor[0]), valor[1]);
                        ordercrr.SetField(fld);
                    }
                }
            }

            if (oriini != 0 && orifim != 0)
            {
                long times = fim - ini;
                logger.Info("=====================================> INICIO ALTERAR ORDEM========> Qtd: " + times);
                for (long i = 0; i < times; i++)
                {
                    ClOrdID     xx  = new ClOrdID(ini.ToString());
                    OrigClOrdID xx2 = new OrigClOrdID(oriini.ToString());
                    ordercrr.ClOrdID     = xx;
                    ordercrr.OrigClOrdID = xx2;

                    bRet = Session.SendToTarget(ordercrr, _session.SessionID);
                    if (!bRet)
                    {
                        logger.Info("erro");
                        break;
                    }
                    if (0 != delay)
                    {
                        Thread.Sleep(delay);
                    }
                    ini++;
                    oriini++;
                }
                logger.Info("=====================================> FIM ALTERAR ORDEM========> Qtd: " + times);
            }
            else
            {
                bRet = Session.SendToTarget(ordercrr, _session.SessionID);
            }

            return(bRet);
        }
Exemplo n.º 32
0
		public static char ToFIX(OrdType ordType)
		{
			switch (ordType)
			{
				case OrdType.Market:
					return '1';
				case OrdType.Limit:
					return '2';
				case OrdType.Stop:
					return '3';
				case OrdType.StopLimit:
					return '4';
				case OrdType.MarketOnClose:
					return '5';
				case OrdType.WithOrWithout:
					return '6';
				case OrdType.LimitOrBetter:
					return '7';
				case OrdType.LimitWithOrWithout:
					return '8';
				case OrdType.OnBasis:
					return '9';
				case OrdType.OnClose:
					return 'A';
				case OrdType.LimitOnClose:
					return 'B';
				case OrdType.ForexMarket:
					return 'C';
				case OrdType.PreviouslyQuoted:
					return 'D';
				case OrdType.PreviouslyIndicated:
					return 'E';
				case OrdType.ForexLimit:
					return 'F';
				case OrdType.ForexSwap:
					return 'G';
				case OrdType.ForexPreviouslyQuoted:
					return 'H';
				case OrdType.Funari:
					return 'I';
				case OrdType.MIT:
					return 'J';
				case OrdType.MarketWithLeftoverAsLimit:
					return 'K';
				case OrdType.PreviousFundValuationPoint:
					return 'L';
				case OrdType.NextFundValuationPoint:
					return 'M';
				case OrdType.Pegged:
					return 'P';
				case OrdType.TrailingStop:
					return 'T';
				case OrdType.TrailingStopLimit:
					return 'S';
				default:
					throw new Exception("unknown: " + ((object)ordType).ToString());
			}
		}
Exemplo n.º 33
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OrderNewSingleRequest" /> class.
        /// </summary>
        /// <param name="exchangeId">Exchange identifier used to identify the routing destination. (required).</param>
        /// <param name="clientOrderId">The unique identifier of the order assigned by the client. (required).</param>
        /// <param name="symbolIdExchange">Exchange symbol. One of the properties (&#x60;symbol_id_exchange&#x60;, &#x60;symbol_id_coinapi&#x60;) is required to identify the market for the new order..</param>
        /// <param name="symbolIdCoinapi">CoinAPI symbol. One of the properties (&#x60;symbol_id_exchange&#x60;, &#x60;symbol_id_coinapi&#x60;) is required to identify the market for the new order..</param>
        /// <param name="amountOrder">Order quantity. (required).</param>
        /// <param name="price">Order price. (required).</param>
        /// <param name="side">side (required).</param>
        /// <param name="orderType">orderType (required).</param>
        /// <param name="timeInForce">timeInForce (required).</param>
        /// <param name="expireTime">Expiration time. Conditionaly required for orders with time_in_force &#x3D; &#x60;GOOD_TILL_TIME_EXCHANGE&#x60; or &#x60;GOOD_TILL_TIME_OEML&#x60;..</param>
        /// <param name="execInst">Order execution instructions are documented in the separate section: &lt;a href&#x3D;\&quot;#oeml-order-params-exec\&quot;&gt;OEML / Starter Guide / Order parameters / Execution instructions&lt;/a&gt; .</param>
        public OrderNewSingleRequest(string exchangeId = default(string), string clientOrderId = default(string), string symbolIdExchange = default(string), string symbolIdCoinapi = default(string), decimal amountOrder = default(decimal), decimal price = default(decimal), OrdSide side = default(OrdSide), OrdType orderType = default(OrdType), TimeInForce timeInForce = default(TimeInForce), DateTime expireTime = default(DateTime), List <ExecInstEnum> execInst = default(List <ExecInstEnum>))
        {
            // to ensure "exchangeId" is required (not null)
            if (exchangeId == null)
            {
                throw new InvalidDataException("exchangeId is a required property for OrderNewSingleRequest and cannot be null");
            }
            else
            {
                this.ExchangeId = exchangeId;
            }

            // to ensure "clientOrderId" is required (not null)
            if (clientOrderId == null)
            {
                throw new InvalidDataException("clientOrderId is a required property for OrderNewSingleRequest and cannot be null");
            }
            else
            {
                this.ClientOrderId = clientOrderId;
            }

            // to ensure "amountOrder" is required (not null)
            if (amountOrder == null)
            {
                throw new InvalidDataException("amountOrder is a required property for OrderNewSingleRequest and cannot be null");
            }
            else
            {
                this.AmountOrder = amountOrder;
            }

            // to ensure "price" is required (not null)
            if (price == null)
            {
                throw new InvalidDataException("price is a required property for OrderNewSingleRequest and cannot be null");
            }
            else
            {
                this.Price = price;
            }

            // to ensure "side" is required (not null)
            if (side == null)
            {
                throw new InvalidDataException("side is a required property for OrderNewSingleRequest and cannot be null");
            }
            else
            {
                this.Side = side;
            }

            // to ensure "orderType" is required (not null)
            if (orderType == null)
            {
                throw new InvalidDataException("orderType is a required property for OrderNewSingleRequest and cannot be null");
            }
            else
            {
                this.OrderType = orderType;
            }

            // to ensure "timeInForce" is required (not null)
            if (timeInForce == null)
            {
                throw new InvalidDataException("timeInForce is a required property for OrderNewSingleRequest and cannot be null");
            }
            else
            {
                this.TimeInForce = timeInForce;
            }

            this.SymbolIdExchange = symbolIdExchange;
            this.SymbolIdCoinapi  = symbolIdCoinapi;
            this.ExpireTime       = expireTime;
            this.ExecInst         = execInst;
        }
Exemplo n.º 34
0
        /// <summary>
        /// ConsistirOrdem - efetuar consistencia do order info
        /// </summary>
        /// <param name="ordem"></param>
        /// <param name="alteracao">flag para indicar se é ou nao alteracao de ordem</param>
        public static void ConsistirOrdem(OrdemInfo ordem, bool alteracao = false)
        {
            // Basic order identification
            if (ordem.Account < 0)
            {
                throw new ArgumentException("Account field must be provided");
            }

            if (alteracao)
            {
                if (ordem.OrigClOrdID == null || ordem.OrigClOrdID.Length <= 0)
                {
                    throw new ArgumentException("OrigClOrdID field must be provided");
                }
            }

            if (ordem.ClOrdID == null || ordem.ClOrdID.Length <= 0)
            {
                throw new ArgumentException("ClOrdID field must be provided");
            }

            // Instrument Identification Block
            if (ordem.Symbol == null || ordem.Symbol.Length <= 0)
            {
                throw new ArgumentException("Symbol must be provided");
            }

            if (ordem.SecurityID == null || ordem.SecurityID.Length <= 0)
            {
                throw new ArgumentException("SecurityID field must be provided");
            }

            if (ordem.OrderQty <= 0)
            {
                throw new ArgumentException("OrderQty must be > 0 ");
            }

            // Cliente
            if (ordem.ExecBroker == null || ordem.ExecBroker.Length <= 0)
            {
                throw new ArgumentException("ExecBroker must be provided");
            }

            TimeInForce tif = TradutorFix.deOrdemValidadeParaTimeInForce(ordem.TimeInForce);

            if (tif == null)
            {
                throw new ArgumentException("TimeInForce is invalid");
            }

            if (ordem.TimeInForce == OrdemValidadeEnum.ValidoAteDeterminadaData)
            {
                if (ordem.ExpireDate == null || ordem.ExpireDate <= DateTime.Now)
                {
                    throw new ArgumentException("ExpireDate is invalid");
                }
            }

            OrdType ordType = TradutorFix.deOrdemTipoParaOrdType(ordem.OrdType);

            if (ordType == null)
            {
                throw new ArgumentException("OrdType is invalid");
            }

            // Verifica envio do preco
            switch (ordem.OrdType)
            {
            case OrdemTipoEnum.Limitada:
            case OrdemTipoEnum.MarketWithLeftOverLimit:
                if (ordem.Price <= 0.0 && ordem.TimeInForce != OrdemValidadeEnum.BoaParaLeilao)
                {
                    throw new ArgumentException("Price must be > 0");
                }
                break;

            case OrdemTipoEnum.StopLimitada:
            case OrdemTipoEnum.StopStart:
                if (ordem.Price <= 0.0)
                {
                    throw new ArgumentException("Price must be > 0");
                }
                if (ordem.StopPrice <= 0.0)
                {
                    throw new ArgumentException("StopPrice must be > 0");
                }
                break;

            case OrdemTipoEnum.Mercado:
            case OrdemTipoEnum.OnClose:
                break;

            default:
                if (ordem.Price <= 0.0)
                {
                    throw new ArgumentException("Price must be > 0");
                }
                break;
            }

            if (ordem.MaxFloor < 0)
            {
                throw new ArgumentException("MaxFloor must be >= 0");
            }

            if (ordem.MinQty < 0)
            {
                throw new ArgumentException("MinQty must be >= 0");
            }

            if (ordem.ExecBroker == null || ordem.ExecBroker.Length <= 0)
            {
                throw new ArgumentException("ExecBroker must be provided");
            }
        }
Exemplo n.º 35
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OrderExecutionReport" /> class.
        /// </summary>
        /// <param name="exchangeId">Exchange identifier used to identify the routing destination. (required).</param>
        /// <param name="clientOrderId">The unique identifier of the order assigned by the client. (required).</param>
        /// <param name="symbolIdExchange">Exchange symbol. One of the properties (&#x60;symbol_id_exchange&#x60;, &#x60;symbol_id_coinapi&#x60;) is required to identify the market for the new order..</param>
        /// <param name="symbolIdCoinapi">CoinAPI symbol. One of the properties (&#x60;symbol_id_exchange&#x60;, &#x60;symbol_id_coinapi&#x60;) is required to identify the market for the new order..</param>
        /// <param name="amountOrder">Order quantity. (required).</param>
        /// <param name="price">Order price. (required).</param>
        /// <param name="side">side (required).</param>
        /// <param name="orderType">orderType (required).</param>
        /// <param name="timeInForce">timeInForce (required).</param>
        /// <param name="expireTime">Expiration time. Conditionaly required for orders with time_in_force &#x3D; &#x60;GOOD_TILL_TIME_EXCHANGE&#x60; or &#x60;GOOD_TILL_TIME_OEML&#x60;..</param>
        /// <param name="execInst">Order execution instructions are documented in the separate section: &lt;a href&#x3D;\&quot;#oeml-order-params-exec\&quot;&gt;OEML / Starter Guide / Order parameters / Execution instructions&lt;/a&gt; .</param>
        /// <param name="clientOrderIdFormatExchange">The unique identifier of the order assigned by the client converted to the exchange order tag format for the purpose of tracking it. (required).</param>
        /// <param name="exchangeOrderId">Unique identifier of the order assigned by the exchange or executing system..</param>
        /// <param name="amountOpen">Quantity open for further execution. &#x60;amount_open&#x60; &#x3D; &#x60;amount_order&#x60; - &#x60;amount_filled&#x60; (required).</param>
        /// <param name="amountFilled">Total quantity filled. (required).</param>
        /// <param name="avgPx">Calculated average price of all fills on this order..</param>
        /// <param name="status">status (required).</param>
        /// <param name="statusHistory">Timestamped history of order status changes..</param>
        /// <param name="errorMessage">Error message..</param>
        /// <param name="fills">Relay fill information on working orders..</param>
        public OrderExecutionReport(string exchangeId = default(string), string clientOrderId = default(string), string symbolIdExchange = default(string), string symbolIdCoinapi = default(string), decimal amountOrder = default(decimal), decimal price = default(decimal), OrdSide side = default(OrdSide), OrdType orderType = default(OrdType), TimeInForce timeInForce = default(TimeInForce), DateTime expireTime = default(DateTime), List <ExecInstEnum> execInst = default(List <ExecInstEnum>), string clientOrderIdFormatExchange = default(string), string exchangeOrderId = default(string), decimal amountOpen = default(decimal), decimal amountFilled = default(decimal), decimal avgPx = default(decimal), OrdStatus status = default(OrdStatus), List <List <string> > statusHistory = default(List <List <string> >), string errorMessage = default(string), List <Fills> fills = default(List <Fills>))
        {
            // to ensure "exchangeId" is required (not null)
            if (exchangeId == null)
            {
                throw new InvalidDataException("exchangeId is a required property for OrderExecutionReport and cannot be null");
            }
            else
            {
                this.ExchangeId = exchangeId;
            }

            // to ensure "clientOrderId" is required (not null)
            if (clientOrderId == null)
            {
                throw new InvalidDataException("clientOrderId is a required property for OrderExecutionReport and cannot be null");
            }
            else
            {
                this.ClientOrderId = clientOrderId;
            }

            // to ensure "amountOrder" is required (not null)
            if (amountOrder == null)
            {
                throw new InvalidDataException("amountOrder is a required property for OrderExecutionReport and cannot be null");
            }
            else
            {
                this.AmountOrder = amountOrder;
            }

            // to ensure "price" is required (not null)
            if (price == null)
            {
                throw new InvalidDataException("price is a required property for OrderExecutionReport and cannot be null");
            }
            else
            {
                this.Price = price;
            }

            // to ensure "side" is required (not null)
            if (side == null)
            {
                throw new InvalidDataException("side is a required property for OrderExecutionReport and cannot be null");
            }
            else
            {
                this.Side = side;
            }

            // to ensure "orderType" is required (not null)
            if (orderType == null)
            {
                throw new InvalidDataException("orderType is a required property for OrderExecutionReport and cannot be null");
            }
            else
            {
                this.OrderType = orderType;
            }

            // to ensure "timeInForce" is required (not null)
            if (timeInForce == null)
            {
                throw new InvalidDataException("timeInForce is a required property for OrderExecutionReport and cannot be null");
            }
            else
            {
                this.TimeInForce = timeInForce;
            }

            // to ensure "clientOrderIdFormatExchange" is required (not null)
            if (clientOrderIdFormatExchange == null)
            {
                throw new InvalidDataException("clientOrderIdFormatExchange is a required property for OrderExecutionReport and cannot be null");
            }
            else
            {
                this.ClientOrderIdFormatExchange = clientOrderIdFormatExchange;
            }

            // to ensure "amountOpen" is required (not null)
            if (amountOpen == null)
            {
                throw new InvalidDataException("amountOpen is a required property for OrderExecutionReport and cannot be null");
            }
            else
            {
                this.AmountOpen = amountOpen;
            }

            // to ensure "amountFilled" is required (not null)
            if (amountFilled == null)
            {
                throw new InvalidDataException("amountFilled is a required property for OrderExecutionReport and cannot be null");
            }
            else
            {
                this.AmountFilled = amountFilled;
            }

            // to ensure "status" is required (not null)
            if (status == null)
            {
                throw new InvalidDataException("status is a required property for OrderExecutionReport and cannot be null");
            }
            else
            {
                this.Status = status;
            }

            this.SymbolIdExchange = symbolIdExchange;
            this.SymbolIdCoinapi  = symbolIdCoinapi;
            this.ExpireTime       = expireTime;
            this.ExecInst         = execInst;
            this.ExchangeOrderId  = exchangeOrderId;
            this.AvgPx            = avgPx;
            this.StatusHistory    = statusHistory;
            this.ErrorMessage     = errorMessage;
            this.Fills            = fills;
        }
Exemplo n.º 36
0
        public static char ToFIX(OrdType ordType)
        {
            switch (ordType)
            {
            case OrdType.Market:
                return('1');

            case OrdType.Limit:
                return('2');

            case OrdType.Stop:
                return('3');

            case OrdType.StopLimit:
                return('4');

            case OrdType.MarketOnClose:
                return('5');

            case OrdType.WithOrWithout:
                return('6');

            case OrdType.LimitOrBetter:
                return('7');

            case OrdType.LimitWithOrWithout:
                return('8');

            case OrdType.OnBasis:
                return('9');

            case OrdType.OnClose:
                return('A');

            case OrdType.LimitOnClose:
                return('B');

            case OrdType.ForexMarket:
                return('C');

            case OrdType.PreviouslyQuoted:
                return('D');

            case OrdType.PreviouslyIndicated:
                return('E');

            case OrdType.ForexLimit:
                return('F');

            case OrdType.ForexSwap:
                return('G');

            case OrdType.ForexPreviouslyQuoted:
                return('H');

            case OrdType.Funari:
                return('I');

            case OrdType.MIT:
                return('J');

            case OrdType.MarketWithLeftoverAsLimit:
                return('K');

            case OrdType.PreviousFundValuationPoint:
                return('L');

            case OrdType.NextFundValuationPoint:
                return('M');

            case OrdType.Pegged:
                return('P');

            case OrdType.TrailingStop:
                return('T');

            case OrdType.TrailingStopLimit:
                return('S');

            default:
                throw new Exception("unknown: " + ((object)ordType).ToString());
            }
        }