Esempio n. 1
0
        public Message CreateNewOrderSingleMessage(string symbol,
                                                   MarketSide marketSide,
                                                   string clOrdID,
                                                   TradingAccount account,
                                                   decimal price,
                                                   decimal quantity,
                                                   OrderType orderType,
                                                   string execID)
        {
            var fOrdType      = TranslateFixFields.Translate(orderType);
            var fSide         = TranslateFixFields.Translate(marketSide);
            var fSymbol       = new Symbol(symbol);
            var fTransactTime = new TransactTime(DateTime.Now);
            var fClOrdID      = new ClOrdID(clOrdID);

            var nos = new NewOrderSingle(fClOrdID,
                                         fSymbol,
                                         fSide,
                                         fTransactTime,
                                         fOrdType)
            {
                OrderQty    = new OrderQty(quantity),
                TimeInForce = new TimeInForce(TimeInForce.GOOD_TILL_CANCEL)
            };

            if (orderType == OrderType.Limit)
            {
                nos.Price = new Price(price);
            }

            return(nos);
        }
    public void process(Message message, SessionID sessionID)
    {
        Message    echo       = (Message)message;
        PossResend possResend = new PossResend(false);

        if (message.getHeader().isSetField(possResend))
        {
            message.getHeader().getField(possResend);
        }

        ClOrdID clOrdID = new ClOrdID();

        message.getField(clOrdID);

        Pair pair = new Pair(clOrdID, sessionID);

        if (possResend.getValue() == true)
        {
            if (orderIDs.Contains(pair))
            {
                return;
            }
        }
        if (!orderIDs.Contains(pair))
        {
            orderIDs.Add(pair, pair);
        }
        try
        {
            Session.sendToTarget(echo, sessionID);
        }
        catch (SessionNotFound) { }
    }
Esempio n. 3
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);
        }
 public Pair(ClOrdID clOrdID, SessionID sessionID)
 {
     this.clOrdID   = clOrdID;
     this.sessionID = sessionID;
     hashCode       =
         ("C:" + clOrdID.ToString() + "S:" + sessionID.ToString()).GetHashCode();
 }
        public static void PlaceNewSingleOrder()
        {
            QuickFix44.NewOrderSingle order = new QuickFix44.NewOrderSingle();

            #region Order Details

            QuickFix.OrderQty   orderQty = new QuickFix.OrderQty(10); order.setField(orderQty);
            QuickFix.Symbol     symbol   = new QuickFix.Symbol("EGS48031C016"); order.setField(symbol);
            QuickFix.SecurityID secID    = new QuickFix.SecurityID("EGS48031C016"); order.setField(secID);
            QuickFix.Side       side     = new QuickFix.Side(Side.SELL); order.setField(side);
            QuickFix.OrdType    ordType  = new QuickFix.OrdType(OrdType.LIMIT); order.setField(ordType);
            QuickFix.Price      price    = new QuickFix.Price(10); order.setField(price);
            Currency            currency = new Currency("EGP"); order.setField(currency);
            Account             acc      = new Account("1003"); order.setField(acc);
            QuickFix.PartyID    custody  = new PartyID("5004"); order.setField(custody);
            TimeInForce         tif      = new TimeInForce(TimeInForce.DAY); order.setField(tif);
            IDSource            ids      = new IDSource("4"); order.setField(ids);
            TransactTime        tt       = new TransactTime(DateTime.Now); order.setField(tt);
            //SenderSubID ss = new SenderSubID("05095a"); order.setField(ss);
            #endregion Order Details

            #region Fix Order Message IDs

            QuickFix.ClOrdID clOrdID = new ClOrdID(Guid.NewGuid().ToString());
            order.setField(clOrdID);

            #endregion Fix Order Message IDs

            #region Exchange
            ExDestination    exd         = new ExDestination("CA"); order.setField(exd);
            TradingSessionID tradSession = new TradingSessionID("NOPL"); order.setField(tradSession);
            #endregion Exchange

            Session.sendToTarget(order, _app.SessionID);
        }
Esempio n. 6
0
  public void process(Message message, SessionID sessionID)
  {
    Message echo = (Message)message;
    PossResend possResend = new PossResend(false);
    if (message.getHeader().isSetField(possResend))
      message.getHeader().getField(possResend);

    ClOrdID clOrdID = new ClOrdID();
    message.getField(clOrdID);

    Pair pair = new Pair(clOrdID, sessionID);

    if (possResend.getValue() == true)
    {
      if (orderIDs.Contains(pair))
        return;
    }
    if(!orderIDs.Contains(pair))
      orderIDs.Add(pair, pair);
    try
    {
      Session.sendToTarget(echo, sessionID);
    }
    catch (SessionNotFound) { }
  }
        public static void ReplaceOrder(OrderID orderID, ClOrdID clOrdID, decimal price, OrdType ordType, TimeInForce timeInForce, Symbol symbol,
                                        OrderQty orderQty, Side side, ExpireTime expireTime, Account account, decimal?slippage)
        {
            QuickFix44.OrderCancelReplaceRequest message = new QuickFix44.OrderCancelReplaceRequest(
                new OrigClOrdID(clOrdID.getValue()),
                clOrdID,
                side,
                new TransactTime(DateTime.UtcNow),
                ordType);

            message.set(orderID);
            message.set(new Price((double)price));
            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);
        }
Esempio n. 8
0
        public static QuickFix.Message ToFixMessage(FixOrder order)
        {
            var dd        = new DataDictionary();
            var clOrdId   = new ClOrdID(Guid.NewGuid().ToString());
            int ordTypeId = (int)order.OrderType;

            var    map  = dd.GetMapForMessage(order.MsgType.ToString());
            string side = ((int)order.Side).ToString();

            var otherSide = side.ToString();
            var orderMsg  = new NewOrderSingle(
                clOrdId,
                new Side(side[0]),
                new TransactTime(DateTime.Now),
                new OrdType('2') //TODO: fix this
                );

            orderMsg.Set(new HandlInst('1'));
            orderMsg.Set(new OrderQty(order.OrderQuantity));
            orderMsg.Set(new TimeInForce('1')); //Day
            orderMsg.Set(new Price(order.Price));


            return(orderMsg);
        }
Esempio n. 9
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());
            }
        }
Esempio n. 10
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());
            }
        }
Esempio n. 11
0
        public void QueueOrderStatus(string clrID, char sideID, string symbolID)
        {
            ClOrdID clOrdID = new ClOrdID(clrID);
            Side    side    = new Side(sideID);
            Symbol  symbol  = new Symbol(symbolID);

            QuickFix42.OrderStatusRequest message = new QuickFix42.OrderStatusRequest(clOrdID, symbol, side);
            SendToServer(message);
        }
Esempio n. 12
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;
        }
Esempio n. 13
0
        public void CancelOrder(string oriID, string clrID, char sideID, string symbolID)
        {
            OrigClOrdID  origClOrdID = new OrigClOrdID(oriID);
            ClOrdID      clOrdID     = new ClOrdID(clrID);
            Side         side        = new Side(sideID);
            Symbol       symbol      = new Symbol(symbolID);
            TransactTime time        = new TransactTime();

            QuickFix42.OrderCancelRequest message = new QuickFix42.OrderCancelRequest(origClOrdID, clOrdID, symbol, side, time);
            message.setInt(38, 0);//委托数量,这里不设置竟无法撤单。
            SendToServer(message);
        }
Esempio 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);
            }
        }
Esempio n. 15
0
        public override void onMessage(QuickFix44.ExecutionReport message, SessionID session)
        {
            OrderID   orderID   = message.getOrderID();
            ClOrdID   clOrdID   = message.getClOrdID();
            OrdStatus ordStatus = message.getOrdStatus();
            Symbol    symbol    = message.getSymbol();

            // firing event

            Console.WriteLine("QuickFix44.ExecutionReport: {0}, {1}, {2}, {3}", orderID, clOrdID, ordStatus, symbol);

            this.fixServices.NotifyExecutionInfo(Counterpart.Dukascopy, DataAdaptors.AdaptExecutionReport(new DukascopyExecutionReportToAdapt(message)));
        }
Esempio 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) {}
        }
Esempio n. 17
0
        public int cancelOrder(OrderStruct os)
        {//will add check in case of already filled, no cancel.
            OrderDAO    ord  = new OrderDAO();
            OrderStruct dbos = new OrderStruct(11, 8);

            if (ord.getOrderFromDB(os.OrderNo, ref dbos) < 0)
            {
                Console.WriteLine("Error : Unable to get order details from DB");
                return(-1);
            }
            Console.WriteLine("DBG: truct val");
            dbos.display();
            string ordStatus = new string(dbos.OrderStatus);

            //if(ordStatus.Equals("CANCELED") || ordStatus.Equals("COMPLETED"))
            //{
            //    Console.WriteLine("Order is already "+ordStatus);
            //    return -1;
            //}
            Console.WriteLine("Order No [" + dbos.OrderNo + "] : Status [" + ordStatus + "]");
            //return -1;
            int ordNo = ord.cancelOrder(ref dbos);

            if (ordNo < 0)
            {
                return(-1);
            }
            Console.WriteLine("TODO: Send FIX - cancel for os.ID");
            //Send FIX - cancel for os.ID

            OrigClOrdID origCLOrdID = new OrigClOrdID(Convert.ToString(dbos.fixAcceptedID));
            ClOrdID     OrdId       = new ClOrdID(Convert.ToString(ordNo));
            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);
            }

            Console.WriteLine("cancelling origOrdId : " + dbos.fixAcceptedID + " newOrdId : " + ordNo);
            Console.WriteLine("symboldata : " + symboldata + " side : " + side);

            var orderCan = new QuickFix.FIX42.OrderCancelRequest(origCLOrdID, OrdId, symbol, side,
                                                                 new TransactTime(DateTime.Now.ToUniversalTime()));

            Session.SendToTarget(orderCan, FixClient.MySess);
            return(os.OrderNo);
        }
Esempio n. 18
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());
        }
Esempio n. 19
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());
            }
        }
        private void addToDictionary(QuickFix42.ExecutionReport msg)
        {
            ClOrdID clID = new ClOrdID();

            msg.getField(clID);
            string ID = clID.getValue();

            if (TodaysMessages.ContainsKey(ID))
            {
                TodaysMessages[ID].Add(msg);
            }
            else
            {
                List <QuickFix42.ExecutionReport> list = new List <QuickFix42.ExecutionReport>();
                list.Add(msg);
                TodaysMessages.Add(ID, list);
            }
        }
Esempio n. 21
0
        public int addOrder(OrderStruct os)
        {
            OrderDAO odao = new OrderDAO();

            Console.WriteLine("Going to call DB");
            int ordNo = odao.insertOrder(os);

            ClOrdID OrdId  = new ClOrdID(Convert.ToString(os.ID));
            string  symbol = sanitiseField(os.symbol);
            var     order  = new QuickFix.FIX42.NewOrderSingle(OrdId, new HandlInst('1'), new Symbol(symbol), new Side(Side.BUY),
                                                               new TransactTime(DateTime.Now.ToUniversalTime()), new OrdType(OrdType.LIMIT));

            order.Price = new Price((decimal)os.price);
            order.SetField(new OrderQty(1));

            Session.SendToTarget(order, FixClient.MySess);
            return(ordNo);
        }
Esempio n. 22
0
  public override void onMessage( QuickFix40.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 );

    QuickFix40.ExecutionReport executionReport = new QuickFix40.ExecutionReport
        ( genOrderID(),
          genExecID(),
          new ExecTransType( ExecTransType.NEW ),
          new OrdStatus ( OrdStatus.FILLED ),
          symbol,
          side,
          orderQty,
          new LastShares ( orderQty.getValue() ),
          new LastPx ( price.getValue() ),
          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 ) {}
  }
Esempio n. 23
0
        private static void _AddToDictionary(QuickFix42.ExecutionReport msg)
        {
            ClOrdID clId = new ClOrdID();

            msg.getField(clId);
            string id = clId.getValue();

            if (TodaysMessages.ContainsKey(id))
            {
                TodaysMessages[id].Add(msg);
            }
            else
            {
                List <QuickFix42.ExecutionReport> list = new List <QuickFix42.ExecutionReport> {
                    msg
                };
                TodaysMessages.Add(id, list);
            }
        }
Esempio n. 24
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())
            });
        }
Esempio n. 25
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());
                }
            }
        }
Esempio n. 26
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())
            });
        }
Esempio n. 27
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);
        }
Esempio n. 28
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);
        }
Esempio n. 29
0
 private void CancelOrder(string id)
 {
     if (id != null)
     {
         if (ordersAll.ContainsKey(id))
         {
             OrigClOrdID orig = new OrigClOrdID(id);
             OrderInfo info = (OrderInfo)ordersAll[id];
             ClOrdID clordid = new ClOrdID(GetNextID());
             Symbol symbol=info.Order .getSymbol ();
             QuickFix.Side side = info.Order.getSide();
             TransactTime time = new TransactTime();
             QuickFix42.OrderCancelRequest cxl = new OrderCancelRequest(orig ,clordid ,symbol ,side,time);
             _quickFixWrapper.Send(cxl);
         }
     }
 }
Esempio n. 30
0
        /*
         * public void ExecOrders(object arg)
         * {
         *  NewOrderSingle ordem = (NewOrderSingle)arg;
         *  long clordid = Convert.ToInt64(DateTime.Now.ToString("yyyyMMddhhmmssfff"));
         *  bool bRet;
         *  logger.Info("=====================================> INICIO ========> Regs: " + _times);
         *  for (int i =0; i<_times; i++)
         *  {
         *      ClOrdID xx = new ClOrdID(clordid++.ToString());
         *      ordem.ClOrdID = xx;
         *      //Thread.Sleep(1);
         *      bRet = Session.SendToTarget(ordem, _session.SessionID);
         *  }
         *  logger.Info("=====================================> FIM ========> Regs: " + _times);
         * }
         */
        public bool AlterarOrdem(OrdemInfo ordem, long ini = 0, long fim = 0, long oriini = 0, long orifim = 0, int delay = 0, string mnemonic = "")
        {
            //Cria a mensagem FIX de NewOrderSingle
            QuickFix.FIX44.OrderCancelReplaceRequest orderCancelReplaceReq = new QuickFix.FIX44.OrderCancelReplaceRequest();

            orderCancelReplaceReq.Set(new OrigClOrdID(ordem.OrigClOrdID));

            if (ordem.Account > 0)
            {
                orderCancelReplaceReq.Set(new Account(ordem.Account.ToString()));
            }
            if (!string.IsNullOrEmpty(mnemonic))
            {
                orderCancelReplaceReq.SetField(new Account(mnemonic), true);
            }


            // Instrument Identification Block
            orderCancelReplaceReq.Set(new Symbol(ordem.Symbol));
            orderCancelReplaceReq.Set(new SecurityID(ordem.SecurityID));
            orderCancelReplaceReq.Set(new SecurityIDSource(SecurityIDSource.EXCHANGE_SYMBOL));

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

            orderCancelReplaceReq.Set(new ClOrdID(ordem.ClOrdID));
            //ordersingle.set(new IDSource());
            if (ordem.Side == OrdemDirecaoEnum.Venda)
            {
                orderCancelReplaceReq.Set(new Side(Side.SELL));
            }
            else
            {
                orderCancelReplaceReq.Set(new Side(Side.BUY));
            }
            orderCancelReplaceReq.Set(new Price(Convert.ToDecimal(ordem.Price)));

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

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

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


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

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

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

            //if (ordem.OrdType == OrdemTipoEnum.StopLimitada )
            //{
            //    ordersingle.set(new StopPx(ordem.StopPx));
            //}

            orderCancelReplaceReq.Set(new TransactTime(DateTime.Now));
            // Cliente
            QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup PartyIDGroup1 = new QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup();
            PartyIDGroup1.Set(new PartyID(ordem.ExecBroker));
            PartyIDGroup1.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE));
            PartyIDGroup1.Set(new PartyRole(PartyRole.ENTERING_TRADER));

            // Corretora
            QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup PartyIDGroup2 = new QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup();
            PartyIDGroup2.Set(new PartyID("227"));
            PartyIDGroup2.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE));
            PartyIDGroup2.Set(new PartyRole(PartyRole.ENTERING_FIRM));

            // Location ID
            QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup PartyIDGroup3 = new QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup();
            if (ordem.SenderLocation != null && ordem.SenderLocation.Length > 0)
            {
                PartyIDGroup3.Set(new PartyID(ordem.SenderLocation));
            }
            else
            {
                PartyIDGroup3.Set(new PartyID("GRA"));
            }
            PartyIDGroup3.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE));
            PartyIDGroup3.Set(new PartyRole(54));

            orderCancelReplaceReq.AddGroup(PartyIDGroup1);
            orderCancelReplaceReq.AddGroup(PartyIDGroup2);
            orderCancelReplaceReq.AddGroup(PartyIDGroup3);

            //BEI - 2012-Nov-14
            if (ordem.ForeignFirm != null && ordem.ForeignFirm.Length > 0)
            {
                QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup PartyIDGroup4 = new QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup();
                PartyIDGroup4.Set(new PartyID(ordem.ForeignFirm));
                PartyIDGroup4.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE));
                PartyIDGroup4.Set(new PartyRole(PartyRole.FOREIGN_FIRM));

                orderCancelReplaceReq.AddGroup(PartyIDGroup4);
            }

            if (ordem.Account > 0)
            {
                QuickFix.FIX44.OrderCancelReplaceRequest.NoAllocsGroup noAllocsGrp = new QuickFix.FIX44.OrderCancelReplaceRequest.NoAllocsGroup();
                noAllocsGrp.Set(new AllocAccount(ordem.Account.ToString()));
                noAllocsGrp.Set(new AllocAcctIDSource(99));
                orderCancelReplaceReq.AddGroup(noAllocsGrp);
            }

            //SelfTradeProtection - 2012-Nov-27
            if (ordem.InvestorID != null && ordem.InvestorID.Length > 0)
            {
                QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup PartyIDGroup5 = new QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup();
                PartyIDGroup5.Set(new PartyID(ordem.InvestorID));
                PartyIDGroup5.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE));
                PartyIDGroup5.Set(new PartyRole(PartyRole.INVESTOR_ID));

                orderCancelReplaceReq.AddGroup(PartyIDGroup5);
            }

            if (ordem.ExecutingTrader != null && ordem.ExecutingTrader.Length > 0)
            {
                QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup PartyIDGroup7 = new QuickFix.FIX44.OrderCancelReplaceRequest.NoPartyIDsGroup();
                PartyIDGroup7.Set(new PartyID(ordem.ExecutingTrader));
                PartyIDGroup7.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE));
                PartyIDGroup7.Set(new PartyRole(PartyRole.EXECUTING_TRADER));

                orderCancelReplaceReq.AddGroup(PartyIDGroup7);
            }

            // Memo Field
            if (ordem.Memo5149 != null && ordem.Memo5149.Length > 0)
            {
                if (ordem.Memo5149.Length > 50)
                {
                    ordem.Memo5149 = ordem.Memo5149.Substring(0, 50);
                }

                StringField memo5149 = new StringField(5149, ordem.Memo5149);

                orderCancelReplaceReq.SetField(memo5149);
            }
            bool bRet = false;

            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());
                    orderCancelReplaceReq.ClOrdID     = xx;
                    orderCancelReplaceReq.OrigClOrdID = xx2;

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

            return(bRet);
        }
Esempio n. 31
0
        public bool CancelarOrdem(OrdemCancelamentoInfo orderCancelInfo, long ini = 0, long fim = 0, long oriini = 0, long orifim = 0, int delay = 0, string mnemonic = "")
        {
            //Cria a mensagem FIX de OrderCancelRequest
            QuickFix.FIX44.OrderCancelRequest orderCancel = new QuickFix.FIX44.OrderCancelRequest();

            if (orderCancelInfo.Account > 0)
            {
                orderCancel.Set(new Account(orderCancelInfo.Account.ToString()));
            }
            if (!string.IsNullOrEmpty(mnemonic))
            {
                orderCancel.SetField(new Account(mnemonic), true);
            }

            orderCancel.Set(new OrigClOrdID(orderCancelInfo.OrigClOrdID));
            orderCancel.Set(new ClOrdID(orderCancelInfo.ClOrdID));
            if (orderCancelInfo.OrderID != null && orderCancelInfo.OrderID.Length > 0)
            {
                orderCancel.Set(new OrderID(orderCancelInfo.OrderID));
            }

            // Instrument Identification Block
            orderCancel.Set(new Symbol(orderCancelInfo.Symbol));
            orderCancel.Set(new SecurityID(orderCancelInfo.SecurityID));
            orderCancel.Set(new SecurityIDSource(SecurityIDSource.EXCHANGE_SYMBOL));

            if (orderCancelInfo.Side == OrdemDirecaoEnum.Venda)
            {
                orderCancel.Set(new Side(Side.SELL));
            }
            else
            {
                orderCancel.Set(new Side(Side.BUY));
            }
            orderCancel.Set(new TransactTime(DateTime.Now));

            //ATP - 2012-10-29
            //Qtde de contratos/papeis a serem cancelados
            orderCancel.Set(new OrderQty(orderCancelInfo.OrderQty));

            // Cliente
            QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup PartyIDGroup1 = new QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup();
            PartyIDGroup1.Set(new PartyID(orderCancelInfo.ExecBroker));
            PartyIDGroup1.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE));
            PartyIDGroup1.Set(new PartyRole(PartyRole.ENTERING_TRADER));

            // Corretora
            QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup PartyIDGroup2 = new QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup();
            PartyIDGroup2.Set(new PartyID("227"));
            PartyIDGroup2.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE));
            PartyIDGroup2.Set(new PartyRole(PartyRole.ENTERING_FIRM));

            QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup PartyIDGroup3 = new QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup();
            if (orderCancelInfo.SenderLocation != null && orderCancelInfo.SenderLocation.Length > 0)
            {
                PartyIDGroup3.Set(new PartyID(orderCancelInfo.SenderLocation));
            }
            else
            {
                PartyIDGroup3.Set(new PartyID("GRA"));
            }
            PartyIDGroup3.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE));
            PartyIDGroup3.Set(new PartyRole(54));

            orderCancel.AddGroup(PartyIDGroup1);
            orderCancel.AddGroup(PartyIDGroup2);
            orderCancel.AddGroup(PartyIDGroup3);

            //BEI - 2012-Nov-14
            if (orderCancelInfo.ForeignFirm != null && orderCancelInfo.ForeignFirm.Length > 0)
            {
                QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup PartyIDGroup4 = new QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup();
                PartyIDGroup4.Set(new PartyID(orderCancelInfo.ForeignFirm));
                PartyIDGroup4.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE));
                PartyIDGroup4.Set(new PartyRole(PartyRole.FOREIGN_FIRM));

                orderCancel.AddGroup(PartyIDGroup4);
            }

            if (orderCancelInfo.ExecutingTrader != null && orderCancelInfo.ExecutingTrader.Length > 0)
            {
                QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup PartyIDGroup7 = new QuickFix.FIX44.OrderCancelRequest.NoPartyIDsGroup();
                PartyIDGroup7.Set(new PartyID(orderCancelInfo.ExecutingTrader));
                PartyIDGroup7.Set(new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE));
                PartyIDGroup7.Set(new PartyRole(PartyRole.EXECUTING_TRADER));

                orderCancel.AddGroup(PartyIDGroup7);
            }

            // Memo Field
            if (orderCancelInfo.Memo5149 != null && orderCancelInfo.Memo5149.Length > 0)
            {
                if (orderCancelInfo.Memo5149.Length > 50)
                {
                    orderCancelInfo.Memo5149 = orderCancelInfo.Memo5149.Substring(0, 50);
                }

                StringField memo5149 = new StringField(5149, orderCancelInfo.Memo5149);

                orderCancel.SetField(memo5149);
            }
            bool bRet = false;

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

                    bRet = Session.SendToTarget(orderCancel, _session.SessionID);
                    if (!bRet)
                    {
                        logger.Info("erro");
                        break;
                    }
                    if (0 != delay)
                    {
                        Thread.Sleep(delay);
                    }
                    ini++;
                    oriini++;
                    //System.Windows.Forms.Application.DoEvents();
                }
                logger.Info("=====================================> FIM CANCELAR ORDEM========> Qtd: " + times);
            }
            else
            {
                bRet = Session.SendToTarget(orderCancel, _session.SessionID);
            }



            return(bRet);
        }
Esempio n. 32
0
 public Pair(ClOrdID clOrdID, SessionID sessionID)
 {
     this.clOrdID = clOrdID;
       this.sessionID = sessionID;
       hashCode =
     ("C:" + clOrdID.ToString() + "S:" + sessionID.ToString()).GetHashCode();
 }
Esempio n. 33
0
        static void Main(string[] args)
        {
            TestFixApp testFixApp = new TestFixApp(args.FirstOrDefault());

            testFixApp.Start();

            Account account = new Account("54b97c9e-202b-11b2-be90-529049f1f1bb");
            ClOrdID clOrdId = new ClOrdID(Guid.NewGuid().ToString());
            Symbol  symbol  = new Symbol("BTC/USD");
            Side    side    = new Side(Side.BUY);

            #region SecurityListRequest
            SecurityListRequest securityListRequest = new SecurityListRequest(
                new SecurityReqID(Guid.NewGuid().ToString()),
                new SecurityListRequestType(SecurityListRequestType.SYMBOL)
                )
            {
                Symbol = symbol
            };
            Console.WriteLine("Press enter to next comand");
            Console.ReadLine();
            testFixApp.Send(securityListRequest);
            testFixApp.WaitResponces(1);
            #endregion SecurityListRequest

            #region MarketDataRequest
            MarketDataRequest marketDataRequest = new MarketDataRequest(
                new MDReqID(Guid.NewGuid().ToString()),
                new SubscriptionRequestType(SubscriptionRequestType.SNAPSHOT),
                new MarketDepth(5))
            {
                MDUpdateType = new MDUpdateType(MDUpdateType.FULL_REFRESH),
            };

            var bid = new MarketDataRequest.NoMDEntryTypesGroup()
            {
                MDEntryType = new MDEntryType(MDEntryType.BID)
            };
            var ask = new MarketDataRequest.NoMDEntryTypesGroup()
            {
                MDEntryType = new MDEntryType(MDEntryType.OFFER)
            };

            var symGroup = new MarketDataRequest.NoRelatedSymGroup
            {
                Symbol = symbol
            };

            marketDataRequest.AddGroup(bid);
            marketDataRequest.AddGroup(ask);
            marketDataRequest.AddGroup(symGroup);


            Console.WriteLine("Press enter to next comand");
            Console.ReadLine();
            testFixApp.Send(marketDataRequest);
            testFixApp.WaitResponces(1);
            #endregion MarketDataRequest

            #region NewOrderSingle
            NewOrderSingle newOrderSingle = new NewOrderSingle(
                clOrdId,
                symbol,
                side,
                new TransactTime(DateTime.Now),
                new OrdType(OrdType.LIMIT))
            {
                OrderQty     = new OrderQty(0.1m),
                Price        = new Price(1m),
                Account      = account,
                AcctIDSource = new AcctIDSource(AcctIDSource.OTHER)
            };

            Console.WriteLine("Press enter to next comand");
            Console.ReadLine();
            testFixApp.Send(newOrderSingle);
            testFixApp.WaitResponces(2);
            #endregion NewOrderSingle

            #region OrderCancelReplaceRequest
            OrderCancelReplaceRequest orderCancelReplaceRequest = new OrderCancelReplaceRequest(
                new OrigClOrdID(clOrdId.ToString()),
                clOrdId = new ClOrdID(Guid.NewGuid().ToString()),
                symbol,
                side,
                new TransactTime(DateTime.Now),
                new OrdType(OrdType.LIMIT))
            {
                Price    = new Price(2m),
                OrderQty = new OrderQty(0.2m)
            };

            Console.WriteLine("Press enter to next comand");
            Console.ReadLine();
            testFixApp.Send(orderCancelReplaceRequest);
            testFixApp.WaitResponces(2);
            #endregion OrderCancelReplaceRequest

            #region OrderStatusRequest
            OrderStatusRequest orderStatusRequest = new OrderStatusRequest(
                clOrdId,
                symbol,
                side
                );
            Console.WriteLine("Press enter to next comand");
            Console.ReadLine();
            testFixApp.Send(orderStatusRequest);
            testFixApp.WaitResponces(1);
            #endregion OrderStatusRequest

            #region OrderCancelRequest
            OrderCancelRequest orderCancelRequest = new OrderCancelRequest(
                new OrigClOrdID(clOrdId.ToString()),
                new ClOrdID(Guid.NewGuid().ToString()),
                symbol,
                side,
                new TransactTime(DateTime.Now)
                )
            {
                OrderQty = new OrderQty(0.1m)
            };

            Console.WriteLine("Press enter to next comand");
            Console.ReadLine();
            testFixApp.Send(orderCancelRequest);
            testFixApp.WaitResponces(3);
            #endregion region OrderCancelRequest

            #region OrderMassStatusRequest
            OrderMassStatusRequest orderMassStatusRequest = new OrderMassStatusRequest(
                new MassStatusReqID(Guid.NewGuid().ToString()),
                new MassStatusReqType(MassStatusReqType.STATUS_FOR_ALL_ORDERS))
            {
                Side   = side,
                Symbol = symbol
            };
            Console.WriteLine("Press enter to next comand");
            Console.ReadLine();
            testFixApp.Send(orderMassStatusRequest);
            #endregion OrderMassStatusRequest

            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
            testFixApp.Stop();
        }
Esempio n. 34
0
        //private void CreateOrder(QuickFix.Side side)
        //{
        //    if (textBox1.Text != string.Empty && textBox2.Text != string.Empty && textBox3.Text != string.Empty)
        //    {
        //        ClOrdID clordid =new ClOrdID ( DateTime.Now.ToString("yyMMddHHmmss"));//Ψһ��Ͷ����ָ����
        //        QuickFix.HandlInst inst = new QuickFix.HandlInst('1'); //1	=	Automated execution order, private, no Broker intervention
        //        //2	=	Automated execution order, public, Broker intervention OK
        //        //3	=	Manual order, best execution
        //        QuickFix.Account account  =new Account ("0103137186"); //2009  11 25 add  �˺�
        //        QuickFix.Symbol symbol = new QuickFix.Symbol(textBox1.Text);
        //        QuickFix.TransactTime time = new QuickFix.TransactTime();
        //        QuickFix.OrdType ordtype = new QuickFix.OrdType('2');//2	=	Limit
        //        QuickFix42.NewOrderSingle message = new QuickFix42.NewOrderSingle(clordid, inst, symbol, side, time, ordtype);
        //        message.setString(44, textBox3.Text);
        //        message.setString(38,textBox2.Text);
        //        message.setString(207, "SSE");   //207   sh �Ϻ�
        //        message.setString(1, "0002077141");//1  Account �˺�
        //        _quickFixWrapper.Send(message);
        //    }
        //    else
        //    {
        //        MessageBox.Show("ָ���������");
        //    }
        //}
        private void CreateOrder()
        {
            if (textBox1.Text != string.Empty && textBox2.Text != string.Empty && comboBox2.SelectedIndex != -1)
            {
                string id = GetNextID();
                ClOrdID clordid = new ClOrdID(id);//Ψһ��Ͷ����ָ����
                //1	=	Automated execution order, private, no Broker intervention
                //2	=	Automated execution order, public, Broker intervention OK
                //3	=	Manual order, best execution
                QuickFix.HandlInst inst = new QuickFix.HandlInst();
                if (comboBox6.SelectedIndex == -1)
                {
                    inst.setValue('1');
                }
                else
                {
                    switch (comboBox6.SelectedItem.ToString())
                    {
                        case "ֱͨ˽��":
                            inst.setValue('1');
                            break;
                        case "ֱͨ����":
                            inst.setValue('2');
                            break;
                        case "����̨":
                            inst.setValue('3');
                            break;
                    }
                }

                QuickFix.Side side = new QuickFix.Side();
                switch (comboBox2.SelectedItem.ToString())
                {
                    case "����":
                        side.setValue('1');
                        break;
                    case "���":
                        side.setValue('2');
                        break;
                    case "���":
                        side.setValue('5');
                        break;
                    case "�깺":
                        side.setValue('D');
                        break;
                    case "���":
                        side.setValue('E');
                        break;
                }
                //QuickFix.Account account = new Account("0103137186"); //2009  11 25 add  �˺�
                QuickFix.OrdType ordtype = new QuickFix.OrdType();
                if (comboBox3.SelectedIndex == -1)
                {
                    ordtype.setValue('1');
                }
                else
                {
                    switch (comboBox3.SelectedItem.ToString())
                    {
                        case "�м�":
                            ordtype.setValue('1');
                            break;
                        case "�޼�":
                            ordtype.setValue('2');
                            break;
                    }
                }

                QuickFix.Symbol symbol = new QuickFix.Symbol(textBox1.Text);
                QuickFix.TransactTime time = new QuickFix.TransactTime();
                QuickFix42.NewOrderSingle message = new QuickFix42.NewOrderSingle(clordid, inst, symbol, side, time, ordtype);
                if (ordtype.getValue () == QuickFix.OrdType.LIMIT)
                {
                    message.setString(44, textBox3.Text);//Limit Price
                }
                message.setString(38, textBox2.Text);//Quantity
                if (textBox1.Text.StartsWith("60"))
                {
                    message.setString(207, "SSE");   //207   sh �Ϻ�
                }
                else if (textBox1.Text.StartsWith("00"))
                {
                    message.setString(207, "SZSE");   //207   sz ����
                }
                //message.setString(1, "0002077141");//1  Account �˺�
                if (!ordersAll.ContainsKey(id))
                {
                    OrderInfo info = new OrderInfo(message);
                    ordersAll.Add(id, info);
                }
                _quickFixWrapper.Send(message);
            }
            else
            {
                MessageBox.Show("ָ���������");
            }
        }
Esempio n. 35
0
        public bool CancelarOrdem(OrdemCancelamentoInfo 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.OrderCancelRequest ordercrr = new QuickFix.FIX42.OrderCancelRequest();

            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));

            // 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);

            // 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 CANCELAR 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 CANCELAR ORDEM========> Qtd: " + times);
            }
            else
            {
                bRet = Session.SendToTarget(ordercrr, _session.SessionID);
            }

            return(bRet);
        }
Esempio n. 36
0
        public int addOrder(OrderStruct os)
        {
            OrderDAO odao = new OrderDAO();

            Console.WriteLine("Going to call DB");
            int ordNo = odao.insertOrder(ref os);

            // Keep the OrderNO for client and pass the OrderID to FIX.
            ClOrdID OrdId      = new ClOrdID(Convert.ToString(os.ID));
            string  symboldata = sanitiseField(os.symbol);

            //check Futures or Options Order
            string exch = new string(os.exch);

            if (exch.Equals("STK"))
            {
                if (os.direction == 'B')
                {
                    Symbol symbol = new Symbol(symboldata);
                    Side   side   = new Side(Side.BUY);
                    int    Qty    = (int)os.quantity;

                    var orderNFO = new QuickFix.FIX42.NewOrderSingle(OrdId, new HandlInst('1'), symbol, side, new TransactTime(DateTime.Now.ToUniversalTime()), new OrdType(OrdType.LIMIT));

                    orderNFO.SetField(new OrderQty(Qty));
                    orderNFO.ExDestination = new ExDestination("NS");
                    orderNFO.SecurityType  = new SecurityType(SecurityType.COMMON_STOCK);
                    //string expiry = new string(os.expiry);
                    //orderNFO.MaturityMonthYear = new MaturityMonthYear(expiry.Substring(0, 6));
                    orderNFO.Account = new Account("D2");
                    OrdType ordType = new OrdType(OrdType.LIMIT);
                    if (os.orderType == 1)
                    {
                        ordType = new OrdType(OrdType.MARKET);
                    }
                    orderNFO.OrdType = ordType;

                    orderNFO.Price = new Price((decimal)os.price);

                    Console.WriteLine("STOCK BUY Order for : " + symbol + "orderType : " + ordType);

                    //Send Future order to fix server
                    Session.SendToTarget(orderNFO, FixClient.MySess);
                }
                else if (os.direction == 'S')
                {
                    Symbol symbol = new Symbol(symboldata);
                    Side   side   = new Side(Side.SELL);
                    int    Qty    = (int)os.quantity;

                    var orderNFO = new QuickFix.FIX42.NewOrderSingle(OrdId, new HandlInst('1'), symbol, side,
                                                                     new TransactTime(DateTime.Now.ToUniversalTime()), new OrdType(OrdType.LIMIT));

                    orderNFO.SetField(new OrderQty(Qty));

                    orderNFO.ExDestination = new ExDestination("NS");
                    orderNFO.SecurityType  = new SecurityType(SecurityType.COMMON_STOCK);
                    //string expiry = new string(os.expiry);
                    //orderNFO.MaturityMonthYear = new MaturityMonthYear(expiry.Substring(0, 6));
                    orderNFO.Account = new Account("D2");
                    OrdType ordType = new OrdType(OrdType.LIMIT);
                    if (os.orderType == 1)
                    {
                        ordType = new OrdType(OrdType.MARKET);
                    }
                    orderNFO.OrdType = ordType;
                    orderNFO.Price   = new Price((decimal)os.price);
                    Console.WriteLine("STOCK SELL Order for : " + symbol + "orderType : " + ordType);
                    //Send Future order to fix server
                    Session.SendToTarget(orderNFO, FixClient.MySess);
                }
            }
            else if (exch.Equals("NFO"))
            {
                if (os.direction == 'B')
                {
                    Symbol symbol = new Symbol(symboldata);
                    Side   side   = new Side(Side.BUY);
                    int    Qty    = (int)os.quantity;

                    var orderNFO = new QuickFix.FIX42.NewOrderSingle(OrdId, new HandlInst('1'), symbol, side,
                                                                     new TransactTime(DateTime.Now.ToUniversalTime()), new OrdType(OrdType.LIMIT));
                    orderNFO.Price = new Price((decimal)os.price);
                    orderNFO.SetField(new OrderQty(Qty));

                    orderNFO.ExDestination = new ExDestination("NS");
                    orderNFO.SecurityType  = new SecurityType(SecurityType.FUTURE);
                    string expiry = new string(os.expiry);
                    orderNFO.MaturityMonthYear = new MaturityMonthYear(expiry.Substring(0, 6));
                    orderNFO.Account           = new Account("D2");
                    OrdType ordType = new OrdType(OrdType.LIMIT);
                    if (os.orderType == 1)
                    {
                        ordType = new OrdType(OrdType.MARKET);
                    }
                    orderNFO.OrdType = ordType;
                    Console.WriteLine("NFO BUY Order for ExpiryDate " + expiry.Substring(0, 6));

                    //Send Future order to fix server
                    Session.SendToTarget(orderNFO, FixClient.MySess);
                }
                else if (os.direction == 'S')
                {
                    Symbol symbol = new Symbol(symboldata);
                    Side   side   = new Side(Side.SELL);
                    int    Qty    = (int)os.quantity;

                    var orderNFO = new QuickFix.FIX42.NewOrderSingle(OrdId, new HandlInst('1'), symbol, side,
                                                                     new TransactTime(DateTime.Now.ToUniversalTime()), new OrdType(OrdType.LIMIT));
                    orderNFO.Price = new Price((decimal)os.price);
                    orderNFO.SetField(new OrderQty(Qty));

                    orderNFO.ExDestination = new ExDestination("NS");
                    orderNFO.SecurityType  = new SecurityType(SecurityType.FUTURE);
                    string expiry = new string(os.expiry);
                    orderNFO.MaturityMonthYear = new MaturityMonthYear(expiry.Substring(0, 6));
                    orderNFO.Account           = new Account("D2");
                    OrdType ordType = new OrdType(OrdType.LIMIT);
                    if (os.orderType == 1)
                    {
                        ordType = new OrdType(OrdType.MARKET);
                    }
                    orderNFO.OrdType = ordType;

                    Console.WriteLine("NFO SELL Order for ExpiryDate " + expiry.Substring(0, 6));
                    //Send Future order to fix server
                    Session.SendToTarget(orderNFO, FixClient.MySess);
                }
            }
            else if (exch.Equals("NOP"))
            {
                if (os.direction == 'B')
                {
                    Symbol symbol  = new Symbol(symboldata);
                    Side   side    = new Side(Side.BUY);
                    int    Qty     = (int)os.quantity;
                    string callput = new string(os.callput);

                    var orderNOP = new QuickFix.FIX42.NewOrderSingle(OrdId, new HandlInst('1'), symbol, side,
                                                                     new TransactTime(DateTime.Now.ToUniversalTime()), new OrdType(OrdType.LIMIT));
                    orderNOP.Price = new Price((decimal)os.price);
                    orderNOP.SetField(new OrderQty(Qty));

                    orderNOP.ExDestination = new ExDestination("NS");
                    orderNOP.SecurityType  = new SecurityType(SecurityType.OPTION);

                    string expiry = new string(os.expiry);
                    orderNOP.MaturityMonthYear = new MaturityMonthYear(expiry.Substring(0, 6));
                    orderNOP.StrikePrice       = new StrikePrice((decimal)(os.strike));
                    if (callput.Equals("CE")) // 0 = PE & 1 = CE
                    {
                        orderNOP.PutOrCall = new PutOrCall(1);
                    }
                    else if (callput.Equals("PE")) // 0 = PE & 1 = CE
                    {
                        orderNOP.PutOrCall = new PutOrCall(0);
                    }
                    orderNOP.Account = new Account("D2");
                    OrdType ordType = new OrdType(OrdType.LIMIT);
                    if (os.orderType == 1)
                    {
                        ordType = new OrdType(OrdType.MARKET);
                    }
                    orderNOP.OrdType = ordType;
                    Console.WriteLine("NOP BUY Order for ExpiryDate " + expiry.Substring(0, 6));
                    //Send Option order to fix server
                    Session.SendToTarget(orderNOP, FixClient.MySess);
                }
                else if (os.direction == 'S')
                {
                    Symbol symbol  = new Symbol(symboldata);
                    Side   side    = new Side(Side.SELL);
                    int    Qty     = (int)os.quantity;
                    string callput = new string(os.callput);

                    var orderNOP = new QuickFix.FIX42.NewOrderSingle(OrdId, new HandlInst('1'), symbol, side,
                                                                     new TransactTime(DateTime.Now.ToUniversalTime()), new OrdType(OrdType.LIMIT));
                    orderNOP.Price = new Price((decimal)os.price);
                    orderNOP.SetField(new OrderQty(Qty));

                    orderNOP.ExDestination = new ExDestination("NS");
                    orderNOP.SecurityType  = new SecurityType(SecurityType.OPTION);

                    string expiry = new string(os.expiry);
                    orderNOP.MaturityMonthYear = new MaturityMonthYear(expiry.Substring(0, 6));
                    orderNOP.StrikePrice       = new StrikePrice((decimal)(os.strike));
                    if (callput.Equals("CE")) // 0 = PE & 1 = CE
                    {
                        orderNOP.PutOrCall = new PutOrCall(1);
                    }
                    else if (callput.Equals("PE")) // 0 = PE & 1 = CE
                    {
                        orderNOP.PutOrCall = new PutOrCall(0);
                    }
                    orderNOP.Account = new Account("D2");
                    OrdType ordType = new OrdType(OrdType.LIMIT);
                    if (os.orderType == 1)
                    {
                        ordType = new OrdType(OrdType.MARKET);
                    }
                    orderNOP.OrdType = ordType;

                    Console.WriteLine("NOP SELL Order for ExpiryDate " + expiry.Substring(0, 6));
                    //Send Option order to fix server
                    Session.SendToTarget(orderNOP, FixClient.MySess);
                }
            }
            return(ordNo);
        }