Beispiel #1
0
        /// <summary>
        /// Create a NewOrderSingle message.
        /// </summary>
        /// <param name="customFields"></param>
        /// <param name="orderType"></param>
        /// <param name="side"></param>
        /// <param name="symbol"></param>
        /// <param name="orderQty"></param>
        /// <param name="tif"></param>
        /// <param name="price">ignored if orderType=Market</param>
        /// <returns></returns>
        static public QuickFix.FIX42.NewOrderSingle NewOrderSingle(
            Dictionary<int,string> customFields,
            OrderType orderType, Side side, string symbol,
            int orderQty, TimeInForce tif, decimal price)
        {
            // hard-coded fields
            QuickFix.Fields.HandlInst fHandlInst = new QuickFix.Fields.HandlInst(QuickFix.Fields.HandlInst.AUTOMATED_EXECUTION_ORDER_PRIVATE);
            
            // from params
            QuickFix.Fields.OrdType fOrdType = FixEnumTranslator.ToField(orderType);
            QuickFix.Fields.Side fSide = FixEnumTranslator.ToField(side);
            QuickFix.Fields.Symbol fSymbol = new QuickFix.Fields.Symbol(symbol);
            QuickFix.Fields.TransactTime fTransactTime = new QuickFix.Fields.TransactTime(DateTime.Now);
            QuickFix.Fields.ClOrdID fClOrdID = GenerateClOrdID();

            QuickFix.FIX42.NewOrderSingle nos = new QuickFix.FIX42.NewOrderSingle(
                fClOrdID, fHandlInst, fSymbol, fSide, fTransactTime, fOrdType);
            nos.OrderQty = new QuickFix.Fields.OrderQty(orderQty);
            nos.TimeInForce = FixEnumTranslator.ToField(tif);

            if (orderType == OrderType.Limit)
                nos.Price = new QuickFix.Fields.Price(price);

            // add custom fields
            foreach (KeyValuePair<int,string> p in customFields)
                nos.SetField(new QuickFix.Fields.StringField(p.Key, p.Value));

            return nos;
        }
 protected OrderSpecification(long instructionId, long instrumentId, TimeInForce timeInForce, decimal quantity,
                              decimal? stopLossPriceOffset, decimal? stopProfitPriceOffset)
 {
     _instructionId = instructionId;
     _instrumentId = instrumentId;
     _timeInForce = timeInForce;
     _quantity = quantity;
     _stopLossPriceOffset = stopLossPriceOffset;
     _stopProfitPriceOffset = stopProfitPriceOffset;
 }
Beispiel #3
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;
        }
 public static IOrder BuildOrder(
     string orderRef,
     DateTime createdTime,
     ICounterparty createdBy,
     OrderType type,
     TimeInForce orderSubType,
     ITransferable item,
     int unitCount,
     Money unitPrice)
 {
     IOrder order = new Order(orderRef, createdTime, createdBy, OrderDirection.Sell, OrderType.LimitOrder, TimeInForce.GoodTillCancelled, item, unitCount, unitPrice);
     return order;
 }
Beispiel #5
0
 public Order(IExecutionProvider provider, Instrument instrument, OrderType type, OrderSide side, double qty, double price = 0.0, double stopPx = 0.0, TimeInForce timeInForce = TimeInForce.Day, string text = "")
     : this()
 {
     this.provider = provider;
     this.instrument = instrument;
     this.type = type;
     this.side = side;
     this.qty = qty;
     this.price = price;
     this.stopPx = stopPx;
     this.timeInForce = timeInForce;
     this.text = text;
     this.portfolio = null;
 }
        public void GtdSameDayTimeInForceEquityOrderExpiresAtMarketClose()
        {
            var utcTime = new DateTime(2018, 4, 27, 10, 0, 0).ConvertToUtc(TimeZones.NewYork);

            var security = new Equity(
                SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(),
                new SubscriptionDataConfig(
                    typeof(TradeBar),
                    Symbols.SPY,
                    Resolution.Minute,
                    TimeZones.NewYork,
                    TimeZones.NewYork,
                    true,
                    true,
                    true
                    ),
                new Cash(CashBook.AccountCurrency, 0, 1m),
                SymbolProperties.GetDefault(CashBook.AccountCurrency),
                ErrorCurrencyConverter.Instance
                );
            var localTimeKeeper = new LocalTimeKeeper(utcTime, TimeZones.NewYork);

            security.SetLocalTimeKeeper(localTimeKeeper);

            var timeInForce     = TimeInForce.GoodTilDate(new DateTime(2018, 4, 27));
            var orderProperties = new OrderProperties {
                TimeInForce = timeInForce
            };
            var order = new LimitOrder(Symbols.SPY, 10, 100, utcTime, "", orderProperties);

            Assert.IsFalse(timeInForce.IsOrderExpired(security, order));

            var fill1 = new OrderEvent(order.Id, order.Symbol, utcTime, OrderStatus.PartiallyFilled, OrderDirection.Buy, order.LimitPrice, 3, 0);

            Assert.IsTrue(timeInForce.IsFillValid(security, order, fill1));

            var fill2 = new OrderEvent(order.Id, order.Symbol, utcTime, OrderStatus.Filled, OrderDirection.Buy, order.LimitPrice, 7, 0);

            Assert.IsTrue(timeInForce.IsFillValid(security, order, fill2));

            localTimeKeeper.UpdateTime(utcTime.AddHours(6).AddSeconds(-1));
            Assert.IsFalse(timeInForce.IsOrderExpired(security, order));

            localTimeKeeper.UpdateTime(utcTime.AddHours(6));
            Assert.IsTrue(timeInForce.IsOrderExpired(security, order));

            Assert.IsTrue(timeInForce.IsFillValid(security, order, fill1));
            Assert.IsTrue(timeInForce.IsFillValid(security, order, fill2));
        }
Beispiel #7
0
 public StopLossDetails(
     PriceValue price,
     double distance,
     ETimeInForce timeInForce,
     DateTime gtdTime,
     ClientExtensions clientExtensions,
     bool guaranteed)
 {
     this.Price            = price;
     this.Distance         = distance;
     this.TimeInForce      = timeInForce.ToString();
     this.GTDTime          = gtdTime;
     this.ClientExtensions = clientExtensions;
     this.Guaranteed       = guaranteed;
 }
Beispiel #8
0
        static TimeInForce parseTif(string tif)
        {
            TimeInForce result = 0;

            if (tif.Equals("gfd", StringComparison.OrdinalIgnoreCase))
            {
                result = TimeInForce.GoodForDay;
            }
            else if (tif.Equals("gtc", StringComparison.OrdinalIgnoreCase))
            {
                result = TimeInForce.GoodTillCancel;
            }

            return(result);
        }
Beispiel #9
0
        public void Properties()
        {
            var time = DateTimeOffset.FromUnixTimeMilliseconds(DateTime.UtcNow.ToTimestamp()).UtcDateTime;

            var               user             = new BinanceApiUser("api-key");
            var               symbol           = Symbol.BTC_USDT;
            const int         id               = 123456;
            const string      clientOrderId    = "test-order";
            const decimal     price            = 4999;
            const decimal     originalQuantity = 1;
            const decimal     executedQuantity = 0.5m;
            const decimal     cummulativeQuoteAssetQuantity = executedQuantity * price;
            const OrderStatus status          = OrderStatus.PartiallyFilled;
            const TimeInForce timeInForce     = TimeInForce.IOC;
            const OrderType   orderType       = OrderType.Market;
            const OrderSide   orderSide       = OrderSide.Sell;
            const decimal     stopPrice       = 5000;
            const decimal     icebergQuantity = 0.1m;
            const bool        isWorking       = true;

            var order = new Order(user, symbol, id, clientOrderId, price, originalQuantity, executedQuantity, cummulativeQuoteAssetQuantity, status, timeInForce, orderType, orderSide, stopPrice, icebergQuantity, time, time, isWorking);

            const string orderRejectedReason = OrderRejectedReason.None;
            const string newClientOrderId    = "new-test-order";

            const long    tradeId          = 12345;
            const long    orderId          = 54321;
            const decimal quantity         = 1;
            const decimal commission       = 10;
            const string  commissionAsset  = "BNB";
            const bool    isBuyer          = true;
            const bool    isMaker          = true;
            const bool    isBestPriceMatch = true;

            var trade = new AccountTrade(symbol, tradeId, orderId, price, quantity, commission, commissionAsset, time, isBuyer, isMaker, isBestPriceMatch);

            const decimal quantityOfLastFilledTrade = 1;

            var args = new AccountTradeUpdateEventArgs(time, order, orderRejectedReason, newClientOrderId, trade, quantityOfLastFilledTrade);

            Assert.Equal(time, args.Time);
            Assert.Equal(order, args.Order);
            Assert.Equal(OrderExecutionType.Trade, args.OrderExecutionType);
            Assert.Equal(orderRejectedReason, args.OrderRejectedReason);
            Assert.Equal(newClientOrderId, args.NewClientOrderId);
            Assert.Equal(trade, args.Trade);
            Assert.Equal(quantityOfLastFilledTrade, args.QuantityOfLastFilledTrade);
        }
Beispiel #10
0
        public void CreateMarketLimitOrder(int id, TimeInForce tif, DateTime?expiry, Side side,
                                           int quantity, int minQuantity = 0,
                                           int maxVisibleQuantity        = int.MaxValue, string smpId = null,
                                           SelfMatchPreventionInstruction smpInstruction = SelfMatchPreventionInstruction.CancelResting)
        {
            var order = new Order(id, Security, OrderType.MarketLimit, tif, expiry, side, null, null,
                                  quantity, minQuantity, maxVisibleQuantity,
                                  smpId, smpInstruction);

            if (quantity < 1)
            {
                FireCreateRejected(order, OrderRejectReason.QuantityTooLow);
                return;
            }

            if (Status != SecurityTradingStatus.Open)
            {
                FireCreateRejected(order, OrderRejectReason.MarketClosed);
                return;
            }


            // TODO: reject if for market-limit, "A designated limit is farther than price bands from current Last Best Price"

            var top = WorkingOrders(order.Side == Side.Buy ? Side.Sell : Side.Buy).FirstOrDefault();

            // check if book is empty
            if (top == null)
            {
                FireCreateRejected(order, OrderRejectReason.NoOrdersToMatchMarketOrder);
                return;
            }

            order.Price = top.Price;

            if (order.TimeInForce == TimeInForce.FillAndKill)
            {
                // TODO: catch earlier?
                if (order.MinQuantity > order.Quantity)
                {
                    FireCreateRejected(order, OrderRejectReason.QuantityOutOfRange);
                    return;
                }
            }

            CreateOrder(order);
            Match();
        }
 public GuaranteedStopLossOrderRejectTransaction(
     string id,
     DateTime time,
     int?userID,
     string accountID,
     string?batchID,
     string?requestID,
     TransactionType type,
     ClientExtensions?clientExtensions,
     string?replacesOrderID,
     string?cancellingTransactionID,
     TimeInForce timeInForce,
     DateTime?gtdTime,
     string tradeID,
     string?clientTradeID,
     decimal price,
     decimal?distance,
     OrderTriggerCondition triggerCondition,
     decimal?guaranteedExecutionPremium,
     GuaranteedStopLossOrderReason reason,
     string?orderFillTransactionID,
     string?intendedReplacesOrderID,
     TransactionRejectReason rejectReason)
     : base(
         id,
         time,
         userID,
         accountID,
         batchID,
         requestID,
         type,
         clientExtensions,
         replacesOrderID,
         cancellingTransactionID,
         timeInForce,
         gtdTime,
         tradeID,
         clientTradeID,
         price,
         distance,
         triggerCondition,
         guaranteedExecutionPremium,
         reason,
         orderFillTransactionID)
 {
     IntendedReplacesOrderID = intendedReplacesOrderID;
     RejectReason            = rejectReason;
 }
Beispiel #12
0
 public Signal(DateTime datetime, SignalType type, SignalSide side, double qty, double strategyPrice, Instrument instrument, string text)
 {
     this.fDateTime      = datetime;
     this.fType          = type;
     this.fSide          = side;
     this.fQty           = qty;
     this.fStrategyPrice = strategyPrice;
     this.fInstrument    = instrument;
     this.fPrice         = this.fInstrument.Price();
     this.fTimeInForce   = TimeInForce.GTC;
     this.fText          = text;
     this.fStrategy      = null;
     this.fStopPrice     = 0.0;
     this.fLimitPrice    = 0.0;
     this.fStatus        = SignalStatus.New;
 }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var         str    = reader.Value.ToString();
            TimeInForce result = TimeInForce.Unknown;

            if (str.Equals("gfd", StringComparison.OrdinalIgnoreCase))
            {
                result = TimeInForce.GoodForDay;
            }
            else if (str.Equals("gtc", StringComparison.OrdinalIgnoreCase))
            {
                result = TimeInForce.GoodTillCancel;
            }

            return(result);
        }
Beispiel #14
0
 public Order(string instructionId, string orderId, long instrumentId, long accountId, Decimal?price, Decimal quantity, Decimal filledQuantity, Decimal cancelledQuantity, OrderType orderType, TimeInForce timeInForce, Decimal?stopLossOffset, Decimal?stopProfitOffset, Decimal?stopReferencePrice, Decimal commission)
 {
     this._instructionId      = instructionId;
     this._orderId            = orderId;
     this._instrumentId       = instrumentId;
     this._accountId          = accountId;
     this._price              = price;
     this._quantity           = quantity;
     this._filledQuantity     = filledQuantity;
     this._cancelledQuantity  = cancelledQuantity;
     this._orderType          = orderType;
     this._timeInForce        = timeInForce;
     this._stopReferencePrice = stopReferencePrice;
     this._stopProfitOffset   = stopProfitOffset;
     this._stopLossOffset     = stopLossOffset;
     this._commission         = commission;
 }
Beispiel #15
0
 /// <summary>
 /// Internal: Output this request.
 /// </summary>
 /// <param name="writer">The destination for the content of this request</param>
 public override void WriteTo(IStructuredWriter writer)
 {
     writer.
     StartElement("req").
     StartElement("body").
     StartElement("order").
     ValueOrNone("instrumentId", InstrumentId).
     ValueOrNone("instructionId", InstructionId).
     ValueOrNone("stopPrice", StopPrice).
     ValueOrNone("quantity", Quantity).
     ValueOrNone("timeInForce", Enum.GetName(TimeInForce.GetType(), TimeInForce)).
     ValueOrNone("stopLossOffset", StopLossPriceOffset).
     ValueOrNone("stopProfitOffset", StopProfitPriceOffset).
     EndElement("order").
     EndElement("body").
     EndElement("req");
 }
Beispiel #16
0
        public static NewOrderUnfilleds ToTransaq(this TimeInForce cond)
        {
            switch (cond)
            {
            case TimeInForce.CancelBalance:
                return(NewOrderUnfilleds.CancelBalance);

            case TimeInForce.MatchOrCancel:
                return(NewOrderUnfilleds.ImmOrCancel);

            case TimeInForce.PutInQueue:
                return(NewOrderUnfilleds.PutInQueue);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            string val = "unknown";

            TimeInForce tif = (TimeInForce)value;

            if (tif == TimeInForce.GoodForDay)
            {
                val = "gfd";
            }
            else if (tif == TimeInForce.GoodTillCancel)
            {
                val = "gtc";
            }

            writer.WriteValue(val);
        }
        public static IFillPoliticsCode ToCode(this TimeInForce politics)
        {
            switch (politics)
            {
            case TimeInForce.FillOrKill:
                return(FillPoliticsCode.FOK);

            case TimeInForce.GoodTillCancel:
                return(FillPoliticsCode.GTC);

            case TimeInForce.ImmediateOrCancel:
                return(FillPoliticsCode.IOC);

            default:
                throw new Exception($"Unknown order fill politics {politics}");
            }
        }
Beispiel #19
0
        public void CreateStopOrder(int id, TimeInForce tif, DateTime?expiry, Side side,
                                    int?stopPrice, int quantity, int minQuantity = 0,
                                    int maxVisibleQuantity = int.MaxValue, string smpId = null,
                                    SelfMatchPreventionInstruction smpInstruction = SelfMatchPreventionInstruction.CancelResting)
        {
            var order = new Order(id, Security, OrderType.Stop, tif, expiry, side, null, stopPrice,
                                  quantity, minQuantity, maxVisibleQuantity,
                                  smpId, smpInstruction);

            if (quantity < 1)
            {
                FireCreateRejected(order, OrderRejectReason.QuantityTooLow);
                return;
            }

            if (Status == SecurityTradingStatus.Close || Status == SecurityTradingStatus.NotAvailable)
            {
                FireCreateRejected(order, OrderRejectReason.MarketClosed);
                return;
            }

            if (order.Side == Side.Buy && stopPrice.Value > lastTradePrice)
            {
                FireCreateRejected(order, OrderRejectReason.StopPriceMustBeLessThanLastTradePrice);
                return;
            }
            if (order.Side == Side.Sell && stopPrice.Value < lastTradePrice)
            {
                FireCreateRejected(order, OrderRejectReason.StopPriceMustBeGreaterThanLastTradePrice);
                return;
            }

            if (order.TimeInForce == TimeInForce.FillAndKill)
            {
                // TODO: catch earlier?
                if (order.MinQuantity > order.Quantity)
                {
                    FireCreateRejected(order, OrderRejectReason.QuantityOutOfRange);
                    return;
                }
            }

            CreateOrder(order);
            order.Status = OrderStatus.Hidden;
            Match();
        }
 /// <summary>
 /// Internal: Output this request.
 /// </summary>
 /// <param name="writer">The destination for the content of this request</param>
 public virtual void WriteTo(IStructuredWriter writer)
 {
     writer.
     StartElement("req").
     StartElement("body").
     StartElement("order").
     ValueOrNone("instrumentId", _instrumentId).
     ValueOrNone("instructionId", _instructionId).
     ValueOrNone("price", GetPrice()).
     ValueOrNone("quantity", _quantity).
     ValueOrNone("timeInForce", Enum.GetName(TimeInForce.GetType(), _timeInForce)).
     ValueOrNone("stopLossOffset", _stopLossPriceOffset).
     ValueOrNone("stopProfitOffset", _stopProfitPriceOffset).
     EndElement("order").
     EndElement("body").
     EndElement("req");
 }
Beispiel #21
0
        public async Task <Trading.OrderResult> PlaceOrder_BuyMarket(
            Data.Format format, string symbol, int shares, TimeInForce timeInForce = TimeInForce.Gtc, bool useMargin = false)
        {
            IAlpacaTradingClient trading = null;
            IAlpacaDataClient    data    = null;

            try {
                if (format == Data.Format.Live)
                {
                    if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Live_Secret))
                    {
                        return(Trading.OrderResult.Fail);
                    }

                    trading = Environments.Live.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Live_Key, Settings.API_Alpaca_Live_Secret));
                    data    = Environments.Live.GetAlpacaDataClient(new SecretKey(Settings.API_Alpaca_Live_Key, Settings.API_Alpaca_Live_Secret));
                }
                else if (format == Data.Format.Paper)
                {
                    if (String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Key) || String.IsNullOrWhiteSpace(Settings.API_Alpaca_Paper_Secret))
                    {
                        return(Trading.OrderResult.Fail);
                    }

                    trading = Environments.Paper.GetAlpacaTradingClient(new SecretKey(Settings.API_Alpaca_Paper_Key, Settings.API_Alpaca_Paper_Secret));
                    data    = Environments.Paper.GetAlpacaDataClient(new SecretKey(Settings.API_Alpaca_Paper_Key, Settings.API_Alpaca_Paper_Secret));
                }

                var account = await trading.GetAccountAsync();

                if (trading == null || account == null ||
                    account.IsAccountBlocked || account.IsTradingBlocked ||
                    account.TradeSuspendedByUser)
                {
                    return(Trading.OrderResult.Fail);
                }

                var order = await trading.PostOrderAsync(MarketOrder.Buy(symbol, shares).WithDuration(timeInForce));

                return(Trading.OrderResult.Success);
            } catch (Exception ex) {
                await Log.Error($"{MethodBase.GetCurrentMethod().DeclaringType}: {MethodBase.GetCurrentMethod().Name}", ex);

                return(Trading.OrderResult.Fail);
            }
        }
Beispiel #22
0
        public TradingSignal(
            Instrument instrument,
            string orderId, OrderCommand command, TradeType tradeType, decimal?price, decimal volume, DateTime time, OrderType orderType = OrderType.Market,
            TimeInForce timeInForce = TimeInForce.FillOrKill)
        {
            Instrument = instrument;

            OrderId = orderId;
            Command = command;

            TradeType   = tradeType;
            Price       = price;
            Volume      = volume;
            Time        = time;
            OrderType   = orderType;
            TimeInForce = timeInForce;
        }
Beispiel #23
0
        public static KucoinTimeInForce ToKucoinTimeInForce(this TimeInForce tif)
        {
            switch (tif)
            {
            case TimeInForce.FOK:
                return(KucoinTimeInForce.FillOrKill);

            case TimeInForce.GTC:
                return(KucoinTimeInForce.GoodTillCancelled);

            case TimeInForce.IOC:
                return(KucoinTimeInForce.ImmediateOrCancel);

            default:
                throw new NotImplementedException();
            }
        }
        public void DeserializesOrderGoodTilDateTimeInForce()
        {
            var expiry          = new DateTime(2018, 5, 26);
            var orderProperties = new OrderProperties {
                TimeInForce = TimeInForce.GoodTilDate(expiry)
            };
            var expected = new MarketOrder(Symbols.BTCUSD, 0.123m, DateTime.Today, "", orderProperties);

            TestOrderType(expected);

            var json   = JsonConvert.SerializeObject(expected);
            var actual = DeserializeOrder <MarketOrder>(json);

            var gtd = (GoodTilDateTimeInForce)actual.Properties.TimeInForce;

            Assert.AreEqual(expiry, gtd.Expiry);
        }
Beispiel #25
0
        public void GtdSameDayTimeInForceForexOrderAfter5PMExpiresAt5PMNextDay()
        {
            // set time to 6:00:00 PM (NY time)
            var utcTime = new DateTime(2018, 4, 27, 18, 0, 0).ConvertToUtc(TimeZones.NewYork);

            var security = new Forex(
                SecurityExchangeHoursTests.CreateForexSecurityExchangeHours(),
                new Cash(CashBook.AccountCurrency, 0, 1m),
                new SubscriptionDataConfig(typeof(QuoteBar), Symbols.EURUSD, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, true),
                SymbolProperties.GetDefault(CashBook.AccountCurrency));
            var localTimeKeeper = new LocalTimeKeeper(utcTime, TimeZones.NewYork);

            security.SetLocalTimeKeeper(localTimeKeeper);

            var timeInForce     = TimeInForce.GoodTilDate(new DateTime(2018, 4, 27));
            var orderProperties = new OrderProperties {
                TimeInForce = timeInForce
            };
            var order = new LimitOrder(Symbols.EURUSD, 10, 100, utcTime, "", orderProperties);

            Assert.IsFalse(timeInForce.IsOrderExpired(security, order));

            var fill1 = new OrderEvent(order.Id, order.Symbol, utcTime, OrderStatus.PartiallyFilled, OrderDirection.Buy, order.LimitPrice, 3, 0);

            Assert.IsTrue(timeInForce.IsFillValid(security, order, fill1));

            var fill2 = new OrderEvent(order.Id, order.Symbol, utcTime, OrderStatus.Filled, OrderDirection.Buy, order.LimitPrice, 7, 0);

            Assert.IsTrue(timeInForce.IsFillValid(security, order, fill2));

            // set time to midnight (NY time)
            localTimeKeeper.UpdateTime(utcTime.AddHours(6));
            Assert.IsFalse(timeInForce.IsOrderExpired(security, order));

            // set time to 4:59:59 PM next day (NY time)
            localTimeKeeper.UpdateTime(utcTime.AddHours(23).AddSeconds(-1));
            Assert.IsFalse(timeInForce.IsOrderExpired(security, order));

            // set time to 5:00:00 PM next day (NY time)
            localTimeKeeper.UpdateTime(utcTime.AddHours(23));
            Assert.IsTrue(timeInForce.IsOrderExpired(security, order));

            Assert.IsTrue(timeInForce.IsFillValid(security, order, fill1));
            Assert.IsTrue(timeInForce.IsFillValid(security, order, fill2));
        }
Beispiel #26
0
 /// <summary>Initializes a new instance of the OrderModel class.</summary>
 /// <param name="tradeType">Possible values include: 'Unknown', 'Buy',
 /// 'Sell'</param>
 /// <param name="orderType">Possible values include: 'Unknown',
 /// 'Market', 'Limit'</param>
 /// <param name="timeInForce">Possible values include:
 /// 'GoodTillCancel', 'FillOrKill'</param>
 /// <param name="dateTime">Date and time must be in 5 minutes threshold
 /// from UTC now</param>
 public OrderModel(TradeType tradeType, OrderType orderType, TimeInForce timeInForce, double volume,
                   DateTime dateTime, string exchangeName = null, string instrument     = null, double?price = null,
                   string orderId           = null, TradeRequestModality modality       = TradeRequestModality.Regular,
                   bool isCancellationTrade = false, string cancellationTradeExternalId = null)
 {
     ExchangeName                = exchangeName;
     Instrument                  = instrument;
     TradeType                   = tradeType;
     OrderType                   = orderType;
     TimeInForce                 = timeInForce;
     Price                       = price;
     Volume                      = volume;
     DateTime                    = dateTime;
     OrderId                     = orderId;
     Modality                    = modality;
     IsCancellationTrade         = isCancellationTrade;
     CancellationTradeExternalId = cancellationTradeExternalId;
 }
Beispiel #27
0
 protected OpeningOrderTransaction(
     string id,
     DateTime time,
     int?userID,
     string accountID,
     string?batchID,
     string?requestID,
     TransactionType type,
     ClientExtensions?clientExtensions,
     string?replacesOrderID,
     string?cancellingTransactionID,
     TimeInForce timeInForce,
     DateTime?gtdTime,
     string instrument,
     decimal units,
     OrderPositionFill positionFill,
     TakeProfitDetails?takeProfitOnFill,
     StopLossDetails?stopLossOnFill,
     TrailingStopLossDetails?trailingStopLossOnFill,
     GuaranteedStopLossDetails?guaranteedStopLossOnFill,
     ClientExtensions?tradeClientExtensions)
     : base(
         id,
         time,
         userID,
         accountID,
         batchID,
         requestID,
         type,
         clientExtensions,
         replacesOrderID,
         cancellingTransactionID,
         timeInForce,
         gtdTime)
 {
     Instrument               = instrument;
     Units                    = units;
     PositionFill             = positionFill;
     TakeProfitOnFill         = takeProfitOnFill;
     StopLossOnFill           = stopLossOnFill;
     TrailingStopLossOnFill   = trailingStopLossOnFill;
     GuaranteedStopLossOnFill = guaranteedStopLossOnFill;
     TradeClientExtensions    = tradeClientExtensions;
 }
Beispiel #28
0
        public void Throws()
        {
            var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

            var               user             = new BinanceApiUser("api-key");
            var               symbol           = Symbol.BTC_USDT;
            const int         id               = 123456;
            const string      clientOrderId    = "test-order";
            const decimal     price            = 4999;
            const decimal     originalQuantity = 1;
            const decimal     executedQuantity = 0.5m;
            const OrderStatus status           = OrderStatus.PartiallyFilled;
            const TimeInForce timeInForce      = TimeInForce.IOC;
            const OrderType   orderType        = OrderType.Market;
            const OrderSide   orderSide        = OrderSide.Sell;
            const decimal     stopPrice        = 5000;
            const decimal     icebergQuantity  = 0.1m;
            const bool        isWorking        = true;

            var order = new Order(user, symbol, id, clientOrderId, price, originalQuantity, executedQuantity, status, timeInForce, orderType, orderSide, stopPrice, icebergQuantity, timestamp, isWorking);

            const OrderRejectedReason orderRejectedReason = OrderRejectedReason.None;
            const string newClientOrderId = "new-test-order";

            const long    tradeId          = 12345;
            const long    orderId          = 54321;
            const decimal quantity         = 1;
            const decimal commission       = 10;
            const string  commissionAsset  = "BNB";
            const bool    isBuyer          = true;
            const bool    isMaker          = true;
            const bool    isBestPriceMatch = true;

            var trade = new AccountTrade(symbol, tradeId, orderId, price, quantity, commission, commissionAsset, timestamp, isBuyer, isMaker, isBestPriceMatch);

            decimal quantityOfLastFilledTrade = 1;

            using (var cts = new CancellationTokenSource())
            {
                Assert.Throws <ArgumentException>("timestamp", () => new AccountTradeUpdateEventArgs(-1, cts.Token, order, orderRejectedReason, newClientOrderId, trade, quantityOfLastFilledTrade));
                Assert.Throws <ArgumentException>("timestamp", () => new AccountTradeUpdateEventArgs(0, cts.Token, order, orderRejectedReason, newClientOrderId, trade, quantityOfLastFilledTrade));
                Assert.Throws <ArgumentNullException>("order", () => new AccountTradeUpdateEventArgs(timestamp, cts.Token, null, orderRejectedReason, newClientOrderId, trade, quantityOfLastFilledTrade));
            }
        }
Beispiel #29
0
        public static string GetTimeInForce(TimeInForce value)
        {
            switch (value)
            {
            case TimeInForce.DayOrder:
                return(fxcore2.Constants.TIF.DAY);

            case TimeInForce.FillOrKill:
                return(fxcore2.Constants.TIF.FOK);

            case TimeInForce.GoodTillCancelled:
                return(fxcore2.Constants.TIF.GTC);

            case TimeInForce.ImmediateOrCancel:
                return(fxcore2.Constants.TIF.IOC);
            }

            throw new ArgumentOutOfRangeException("value");
        }
Beispiel #30
0
 public ExecutionCommand(ExecutionCommand command)
 {
     this.id           = command.id;
     this.providerId   = command.providerId;
     this.portfolioId  = command.portfolioId;
     this.transactTime = command.transactTime;
     this.dateTime     = command.dateTime;
     this.instrument   = command.instrument;
     this.provider     = command.provider;
     this.portfolio    = command.portfolio;
     this.side         = command.side;
     this.orderType    = command.OrdType;
     this.timeInForce  = command.timeInForce;
     this.price        = command.price;
     this.stopPx       = command.stopPx;
     this.qty          = command.qty;
     this.oCA          = command.oCA;
     this.text         = command.text;
 }
 public TrailingStopLossOrderRejectTransaction()
 {
     this.TransactionID           = new TransactionID();
     this.Time                    = new DateTime();
     this.AccountID               = new AccountID();
     this.BatchID                 = new TransactionID();
     this.RequestID               = new RequestID();
     this.Type                    = new TransactionType(ETransactionType.TRAILING_STOP_LOSS_ORDER_REJECT);
     this.TradeID                 = new TradeID();
     this.ClientTradeID           = new ClientID();
     this.TimeInForce             = new TimeInForce(ETimeInForce.GTC);
     this.GTDTime                 = new DateTime();
     this.TriggerCondition        = new OrderTriggerCondition(EOrderTriggerCondition.DEFAULT);
     this.Reason                  = new TrailingStopLossOrderReason();
     this.ClientExtensions        = new ClientExtensions();
     this.OrderFillTransactionID  = new TransactionID();
     this.IntendedReplacesOrderID = new OrderID();
     this.RejectReason            = new TransactionRejectReason();
 }
        internal static DateTime GetOrderExpireDateByTIF(TimeInForce tif, DateTime orderExpireDate, DateTime utc)
        {
            switch (tif)
            {
            case TimeInForce.Day:
                return(utc.AddDays(1));

            case TimeInForce.FOC:
            case TimeInForce.IOC:
                return(utc.AddMinutes(1));

            case TimeInForce.GTC:
                return(utc.AddYears(10));

            case TimeInForce.GTD:
            default:
                return(orderExpireDate);
            }
        }
Beispiel #33
0
 public StopLossOrderTransaction()
 {
     this.Id                      = new TransactionID();
     this.Time                    = new DateTime();
     this.AccountID               = new AccountID();
     this.BatchID                 = new TransactionID();
     this.RequestID               = new RequestID();
     this.Type                    = new TransactionType(ETransactionType.STOP_LOSS_ORDER);
     this.TradeID                 = new TradeID();
     this.ClientTradeID           = new ClientID();
     this.Price                   = new PriceValue();
     this.TimeInForce             = new TimeInForce(ETimeInForce.GTC);
     this.GTDTime                 = new DateTime();
     this.TriggerCondition        = new OrderTriggerCondition(EOrderTriggerCondition.DEFAULT);
     this.Reason                  = new StopLossOrderReason();
     this.ClientExtensions        = new ClientExtensions();
     this.OrderFillTransactionID  = new TransactionID();
     this.ReplacesOrderID         = new OrderID();
     this.CancellingTransactionID = new TransactionID();
 }
Beispiel #34
0
 public StopLossOrderRejectTransaction()
 {
     this.Id                      = new TransactionID();
     this.Time                    = new DateTime();
     this.AccountID               = new AccountID();
     this.BatchID                 = new TransactionID();
     this.RequestID               = new RequestID();
     this.Type                    = new TransactionType(ETransactionType.STOP_LOSS_ORDER_REJECT);
     this.TradeID                 = new TradeID();
     this.ClientTradeID           = new ClientID();
     this.Price                   = new PriceValue();
     this.TimeInForce             = new TimeInForce(ETimeInForce.GTC);
     this.GTDTime                 = new DateTime();
     this.TriggerCondition        = new OrderTriggerCondition();
     this.Reason                  = new StopLossOrderReason();
     this.ClientExtensions        = new ClientExtensions();
     this.OrderFillTransactionID  = new TransactionID();
     this.IntendedRepalcesOrderID = new OrderID();
     this.RejectReason            = new TransactionRejectReason();
 }
Beispiel #35
0
 public Order(int id, Security security, OrderType type, TimeInForce tif, DateTime?expiry, Side side,
              int?price, int?stopPrice, int quantity, int minQuantity, int?maxVisibleQuantity,
              string selfMatchId, SelfMatchPreventionInstruction selfMatchMode)
 {
     Id                 = id;
     Security           = security;
     Type               = type;
     TimeInForce        = tif;
     ExpireDate         = expiry;
     Side               = side;
     Price              = price;
     StopPrice          = stopPrice;
     Quantity           = quantity;
     FilledQuantity     = 0;
     RemainingQuantity  = quantity;
     MinQuantity        = minQuantity;
     MaxVisibleQuantity = maxVisibleQuantity ?? int.MaxValue;
     SelfMatchId        = selfMatchId;
     SelfMatchMode      = selfMatchMode;
 }
Beispiel #36
0
 public static char ToFIX(TimeInForce timeInForce)
 {
     switch (timeInForce)
     {
         case TimeInForce.Undefined:
             return char.MinValue;
         case TimeInForce.Day:
             return '0';
         case TimeInForce.GTC:
             return '1';
         case TimeInForce.OPG:
             return '2';
         case TimeInForce.IOC:
             return '3';
         case TimeInForce.FOK:
             return '4';
         case TimeInForce.GTX:
             return '5';
         case TimeInForce.GoodTillDate:
             return '6';
         case TimeInForce.AtTheClose:
             return '7';
         case TimeInForce.GoodForSeconds:
             return 'X';
         default:
             throw new ArgumentException("" + ((object)timeInForce).ToString());
     }
 }
Beispiel #37
0
		public ExecutionReport(ExecutionReport report)
		{
			this.dateTime = report.dateTime;
			this.instrument = report.instrument;
			this.currencyId = report.currencyId;
			this.execType = report.execType;
			this.ordType = report.ordType;
			this.side = report.side;
			this.timeInForce = report.timeInForce;
			this.ordStatus = report.ordStatus;
			this.order = report.order;
			this.commandID = report.commandID;
			this.lastPx = report.lastPx;
			this.avgPx = report.avgPx;
			this.ordQty = report.ordQty;
			this.cumQty = report.cumQty;
			this.lastQty = report.lastQty;
			this.leavesQty = report.leavesQty;
			this.price = report.price;
			this.stopPx = report.stopPx;
			this.commission = report.commission;
		}
		private ExecutionMessage CreateMessage(DateTime localTime, DateTimeOffset serverTime, Sides side, decimal price, decimal volume, bool isCancelling = false, TimeInForce tif = TimeInForce.PutInQueue)
		{
			if (price <= 0)
				throw new ArgumentOutOfRangeException(nameof(price), price, LocalizedStrings.Str1144);

			//if (volume <= 0)
			//	throw new ArgumentOutOfRangeException("volume", volume, "Объем задан не верно.");

			if (volume == 0)
				volume = _volumeRandom.Next(10, 100);

			return new ExecutionMessage
			{
				Side = side,
				OrderPrice = price,
				Volume = volume,
				ExecutionType = ExecutionTypes.OrderLog,
				IsCancelled = isCancelling,
				SecurityId = SecurityId,
				LocalTime = localTime,
				ServerTime = serverTime,
				TimeInForce = tif,
			};
		}
Beispiel #39
0
		public virtual SingleOrder BuyLimit(Instrument instrument, double price, TimeInForce timeInForce)
		{
			return this.BuyLimit(instrument, price, timeInForce, this.Strategy.Name);
		}
Beispiel #40
0
        /// <summary>
        /// Default Constructor
        /// </summary>
        public Order()
        {
            openClose = "O";
            origin = OrderOrigin.Customer;
            transmit = true;
            tif = TimeInForce.Day;
            designatedLocation = "";
            minQty = int.MaxValue;
            percentOffset = double.MaxValue;
            nbboPriceCap = decimal.MaxValue;
            startingPrice = decimal.MaxValue;
            stockRefPrice = double.MaxValue;
            delta = double.MaxValue;
            stockRangeLower = double.MaxValue;
            stockRangeUpper = double.MaxValue;
            volatility = double.MaxValue;
            volatilityType = VolatilityType.Undefined;
            deltaNeutralOrderType = OrderType.Empty;
            deltaNeutralAuxPrice = double.MaxValue;
            referencePriceType = int.MaxValue;
            trailStopPrice = decimal.MaxValue;
            basisPoints = decimal.MaxValue;
            basisPointsType = int.MaxValue;
            scaleInitLevelSize = int.MaxValue;
            scaleSubsLevelSize = int.MaxValue;
            scalePriceIncrement = decimal.MaxValue;
            faMethod = FinancialAdvisorAllocationMethod.None;
            notHeld = false;
            exemptCode = -1;

            optOutSmartRouting = false;
            deltaNeutralConId = 0;
            deltaNeutralOrderType = OrderType.Empty;
            deltaNeutralSettlingFirm = string.Empty;
            deltaNeutralClearingAccount = string.Empty;
            deltaNeutralClearingIntent = string.Empty;

            DeltaNeutralOpenClose = "";
            DeltaNeutralShortSale = false;
            DeltaNeutralShortSaleSlot = 0;
            DeltaNeutralDesignatedLocation = "";
            referencePriceType = int.MaxValue;
            trailStopPrice = decimal.MaxValue;
            TrailingPercent = double.MaxValue;
            BasisPoints = decimal.MaxValue;
            basisPointsType = int.MaxValue;
            scaleInitLevelSize = int.MaxValue;
            scaleSubsLevelSize = int.MaxValue;
            scalePriceIncrement = decimal.MaxValue;
            ScalePriceAdjustValue = double.MaxValue;
            ScalePriceAdjustInterval = int.MaxValue;
            ScaleProfitOffset = double.MaxValue;
            ScaleAutoReset = false;
            ScaleInitPosition = int.MaxValue;
            ScaleInitFillQty = int.MaxValue;
            ScaleRandomPercent = false;
            ScaleTable = "";
            whatIf = false;
            notHeld = false;
            Conditions = new List<OrderCondition>();
            TriggerPrice = double.MaxValue;
            LmtPriceOffset = double.MaxValue;
            AdjustedStopPrice = double.MaxValue;
            AdjustedStopLimitPrice = double.MaxValue;
            AdjustedTrailingAmount = double.MaxValue;
            ExtOperator = "";
        }
Beispiel #41
0
 /// <summary>
 /// Default Constructor
 /// </summary>
 public Order()
 {
     openClose = "O";
     origin = OrderOrigin.Customer;
     transmit = true;
     tif = TimeInForce.Day;
     designatedLocation = "";
     minQty = Int32.MaxValue;
     percentOffset = Double.MaxValue;
     nbboPriceCap = decimal.MaxValue;
     startingPrice = decimal.MaxValue;
     stockRefPrice = Double.MaxValue;
     delta = Double.MaxValue;
     stockRangeLower = Double.MaxValue;
     stockRangeUpper = Double.MaxValue;
     volatility = Double.MaxValue;
     volatilityType = VolatilityType.Undefined;
     deltaNeutralOrderType = OrderType.Empty;
     deltaNeutralAuxPrice = Double.MaxValue;
     referencePriceType = Int32.MaxValue;
     trailStopPrice = decimal.MaxValue;
     basisPoints = decimal.MaxValue;
     basisPointsType = Int32.MaxValue;
     scaleInitLevelSize = Int32.MaxValue;
     scaleSubsLevelSize = Int32.MaxValue;
     scalePriceIncrement = decimal.MaxValue;
     faMethod = FinancialAdvisorAllocationMethod.None;
     notHeld = false;
     exemptCode = -1;
     
     optOutSmartRouting = false;
     deltaNeutralConId = 0;
     deltaNeutralOrderType = OrderType.Empty;
     deltaNeutralSettlingFirm = string.Empty;
     deltaNeutralClearingAccount = string.Empty;
     deltaNeutralClearingIntent = string.Empty;
 }
 /// <summary>
 /// Construct a Limit Order that contains a stop loss and/or stop profit price offset.
 /// </summary>
 /// <param name="instructionId">The client specified instruction id, should be unique for an account.</param>
 /// <param name="instrumentId">The instrument id of the OrderBook to place the order on.</param>
 /// <param name="price">The price for the order to be placed into the book if not aggressively filled.</param>
 /// <param name="quantity">The size of the limit order.  The side of the order is inferred
 /// from the sign of the quantity.  A positive value is a buy, negative is sell.</param>
 /// <param name="timeInForce">A <see cref="TimeInForce"/> that describes the behaviour of the order
 /// if not fully filled</param>
 public LimitOrderSpecification(long instructionId, long instrumentId, decimal price, decimal quantity, TimeInForce timeInForce) : this(instructionId, instrumentId, price, quantity, timeInForce, null, null)
 {
 }
Beispiel #43
0
		public virtual SingleOrder BuyLimit(double price, TimeInForce timeInForce, string text)
		{
			return this.BuyLimit(this.instrument, price, timeInForce, text);
		}
Beispiel #44
0
		public virtual SingleOrder SellLimit(double price, TimeInForce timeInForce)
		{
			return this.SellLimit(this.instrument, price, timeInForce);
		}
 /// <summary>
 /// Construct a Limit Order that contains a stop loss and/or stop profit price offset.
 /// </summary>
 /// <param name="instructionId">The client specified instruction id, should be unique for an account.</param>
 /// <param name="instrumentId">The instrument id of the OrderBook to place the order on.</param>
 /// <param name="price">The price for the order to be placed into the book if not aggressively filled.</param>
 /// <param name="quantity">The size of the limit order.  The side of the order is inferred
 /// from the sign of the quantity.  A positive value is a buy, negative is sell.</param>
 /// <param name="timeInForce">A <see cref="TimeInForce"/> that describes the behaviour of the order
 /// if not fully filled</param>
 /// <param name="stopLossPriceOffset">The stop loss offset, set this to null to not specify a stop loss.</param>
 /// <param name="stopProfitPriceOffset">The stop profit offset, set this to null to not specify a stop profit.</param>
 public LimitOrderSpecification(long instructionId, long instrumentId, decimal price, decimal quantity, TimeInForce timeInForce, decimal? stopLossPriceOffset, decimal? stopProfitPriceOffset) :
     base(instructionId, instrumentId, timeInForce, quantity, stopLossPriceOffset, stopProfitPriceOffset)
 {
     Price = price;
 }
Beispiel #46
0
 public Order(IExecutionProvider provider, Instrument instrument, OrderType type, OrderSide side, double qty, double price = 0, double stopPx = 0, TimeInForce timeInForce = TimeInForce.Day, string text = "")
         : this()
     {
         Provider = provider;
         Instrument = instrument;
         Type = type;
         Side = side;
         Qty = qty;
         Price = price;
         StopPx = stopPx;
         TimeInForce = timeInForce;
         Text = text;
     }
Beispiel #47
0
 public Order(IExecutionProvider provider, Portfolio portfolio, Instrument instrument, OrderType type, OrderSide side, double qty, double price = 0, double stopPx = 0, TimeInForce timeInForce = TimeInForce.Day, byte routeId = 0, string text = "")
    : this(provider, instrument, type, side, qty, price, stopPx, timeInForce, text = "")
 {
     Portfolio = portfolio;
     RouteId = routeId;
 }
Beispiel #48
0
		public ExecutionCommand(ExecutionCommand command)
		{
			this.id = command.id;
			this.providerId = command.providerId;
			this.portfolioId = command.portfolioId;
			this.transactTime = command.transactTime;
			this.dateTime = command.dateTime;
			this.instrument = command.instrument;
			this.provider = command.provider;
			this.portfolio = command.portfolio;
			this.side = command.side;
			this.orderType = command.OrdType;
			this.timeInForce = command.timeInForce;
			this.price = command.price;
			this.stopPx = command.stopPx;
			this.qty = command.qty;
			this.oCA = command.oCA;
			this.text = command.text;
		}
 /// <summary>
 /// constructor
 /// </summary>
 /// <param name="order"></param>
 public OrderInfo(OrderInfo order)
 {
     this.m_nLeavesQty = order.m_nLeavesQty;
     this.m_nOrderQty = order.m_nOrderQty;
     this.m_dPrice = order.m_dPrice;
     this.m_nSecondBOID = order.m_nSecondBOID;
     this.m_sExecutionReportStatus = order.m_sExecutionReportStatus;
     this.m_TransactTime = order.m_TransactTime;
     this.m_instrument = order.m_instrument;
     this.m_nCumQty = order.m_nCumQty;
     this.m_sClOrdID = order.m_sClOrdID;
     this.m_sSide = order.m_sSide;
     this.m_sExecutionReportStatus = order.m_sExecutionReportStatus;
     this.m_sTickerMnemonic = order.m_sTickerMnemonic;
     this.m_sTimeInForce = order.m_sTimeInForce;
     this.m_sOrderType = order.m_sOrderType;
     this.PrimaryBOID = order.PrimaryBOID;
     this.m_iAccountID = order.m_iAccountID;
 }
        /// <summary>
        /// Parse msg for instrument data
        /// </summary>
        /// <param name="FIXMsg"></param>
        /// <returns></returns>
        public bool ParseFIX(EASYROUTERCOMCLIENTLib.IFIXMessage FIXMsg)
        {
            try
            {
                //exchaange
                string sExchange = FIXMsg.get_AsString(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagSecurityExchange);
                //Esexchange
                string sESExchange = FIXMsg.get_AsString(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagESExchange);
                //type of instrument
                string sSecurityType = FIXMsg.get_AsString(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagSecurityType);
                //commodity symbol
                string sSymbol = FIXMsg.get_AsString(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagSymbol);
                //easyscreen TE symbol
                string sESTickerMnemonic = FIXMsg.get_AsString(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagESTickerMnemonic);

                string sESTickerDesc = FIXMsg.get_AsString(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagESTickerDesc);
                //exchange code
                string sTickerSymbol = FIXMsg.get_AsString(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagESTickerSymbol);
                int nESOrderType = FIXMsg.get_AsNumber(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagESSupportPriceType);
                int nESTimeType = FIXMsg.get_AsNumber(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagESSupportTimeType);
                bool bESSupportEdit = FIXMsg.get_AsBoolean(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagESSupportEdit);
                int lESPriceFormatCode = FIXMsg.get_AsNumber(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagESPriceFormatCode);

                m_sSymbol = sSymbol;
                m_sESTickerMnemonic = sESTickerMnemonic;
                m_sESTickerDesc = sESTickerDesc;
                m_sESTickerSymbol = sTickerSymbol;
                m_eOrderType = (OrderType)nESOrderType;
                m_eTimeType = (TimeInForce)nESTimeType;
                m_bESSupportEdit = bESSupportEdit;
                m_lESPriceFormatCode = lESPriceFormatCode;

                int nOptionType = 0;
                if(FIXMsg.GetNumber(out nOptionType,EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagPutOrCall))
                {
                    //defaults to 1 - call if never here
                    m_nOptionType = nOptionType;
                }

                m_sCFICode = FIXMsg.get_AsString(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagCFICode);

                m_sCurrency = FIXMsg.get_AsString(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagCurrency);
                m_dUnitTickValue = FIXMsg.get_AsDouble(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagESUnitTickValue);
                m_dCompositeDelta = FIXMsg.get_AsDouble(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagESCompositeDelta);
                m_dESShortOptAdjust = FIXMsg.get_AsDouble(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagESShortOptAdjust);
                m_nESDecimalPlaces = FIXMsg.get_AsNumber(EASYROUTERCOMCLIENTLib.FIXTagConstants.esFIXTagESDecimalPlaces);

                AdditonalUpdates(FIXMsg);
            }
            catch(Exception)
            {
                return false;
            }
            return true;
        }
Beispiel #51
0
 public void setOrderValidity(TimeInForce val)
 {
     ContextModulePINVOKE.Order_setOrderValidity(swigCPtr, (int)val);
 }
 private bool SetFIXTimeInForce(string strTimeInForce)
 {
     switch (strTimeInForce)
     {
         case FIXTimeInForceConstants.esFIXTimeInForceGoodTillCancel: m_sTimeInForce = TimeInForce.GoodTillCancelled; return true;
         case FIXTimeInForceConstants.esFIXTimeInForceDay: m_sTimeInForce = TimeInForce.StandardOrders; return true;
         case FIXTimeInForceConstants.esFIXTimeInForceFillOrKill: m_sTimeInForce = TimeInForce.FillOrKill; return true;
         default: return false;
     }
 }
Beispiel #53
0
		public virtual SingleOrder BuyLimit(Instrument instrument, double price, TimeInForce timeInForce, string text)
		{
			if (!this.Strategy.IsInstrumentActive(instrument))
				return (SingleOrder)null;
			return this.Strategy.BgvpSPpUAD(new Signal(Clock.Now, ComponentType.CrossEntry, SignalType.Limit, SignalSide.Buy, instrument, text)
			{
				LimitPrice = price,
				TimeInForce = timeInForce
			});
		}
Beispiel #54
0
        public Order(
            string orderRef,
            DateTime createdTime,
            ICounterparty createdBy,
            OrderDirection orderDirection,
            OrderType type,
            TimeInForce timeInForce,
            ITransferable item,
            int unitCount,
            Money unitPrice)
        {
            OrderRef = orderRef;
            CreatedTime = createdTime;
            CreatedBy = createdBy;
            Direction = orderDirection;
            Type = type;
            TimeInForce = timeInForce;
            Item = item;
            Size = unitCount;
            Price = unitPrice;

            FilledSize = 0;
            Status = OrderStatus.Created;

            Trades = new List<Trade>();
        }
Beispiel #55
0
 public Order(Order order)
     : base()
 {
     this.id = -1;
     this.oCA = "";
     this.text = "";
     this.id = order.id;
     this.providerId = order.providerId;
     this.portfolioId = order.portfolioId;
     this.transactTime = order.transactTime;
     this.dateTime = order.dateTime;
     this.instrument = order.instrument;
     this.provider = order.provider;
     this.portfolio = order.portfolio;
     this.status = order.status;
     this.side = order.side;
     this.type = order.type;
     this.timeInForce = order.timeInForce;
     this.price = order.price;
     this.stopPx = order.stopPx;
     this.avgPx = order.avgPx;
     this.qty = order.qty;
     this.cumQty = order.cumQty;
     this.text = order.text;
     this.commands = order.commands;
     this.reports = order.reports;
     this.messages = order.messages;
 }
Beispiel #56
0
 public Order(string symbol,int size, long id,  decimal p, decimal s, decimal t, int date, int time, TimeInForce tif = TimeInForce.DAY)
 {
     this.FullSymbol = symbol;
     this.OrderSize = size;
     this.Id = id;
     this.OrderDate = date;
     this.OrderTime = time;
     this.LimitPrice = p;
     this.StopPrice = s;
     this.TrailPrice = t;
     this.Account = "";
     this.TIF = tif;
     this.Currency = "USD";
 }
        /// <summary>
        /// Submit new order
        /// </summary>
        /// <param name="sTE">ES Ticker Mnemomic (internal ER symbol for instrument</param>
        /// <param name="bBuy">is it a buy or sell</param>
        /// <param name="dPrice">price of order</param>
        /// <param name="nVolume">volume of order</param>
        /// <returns></returns>
        public bool SubmitNewOrder(string sTE, bool bBuy, double? dPrice, int nVolume,  OrderType sOrderType, TimeInForce sTimeInForce)
        {
            /*
                BodyLength=232
                MsgType=NewOrderSingle<D>
                ESTickerMnemonic=3FX:EUR-GBP
                ESTickerSymbol=EUR-GBP
                ESExchange=F
                ESPriceFormatCode=0
                SecurityExchange=3
                PutOrCall=OptionTypePut<0>
                SecurityType=FOR
                Symbol=EUR
                CFICode=MRCXXX
                Currency=EUR
                ESDecimalPlaces=4
                ESUnitTickValue=0.000000
                ESCompositeDelta=0.000000
                ESShortOptAdjust=0.000000
                Side=SideSell<2>
                OpenClose=Open<O>
                ESAccountID=9
                ESAccountName=apj
                HandlInst=2
                ESDefaultFieldSanityCheck=True
                OrdType=OrderTypeLimit<2>
                TimeInForce=TimeInForceImmediateOrCancel<3>
                Price=0.67501
                StopPx=0
                TradingSessionID=2
                OrderQty=1
             */

            OrderInfo order = new OrderInfo(sTE);
            order.Price = dPrice;
            order.OrderQty = nVolume;

            if (bBuy == true)
            {
                order.Side = MESSAGEFIX3Lib.FIXSideConstants.esFIXSideBuy;
            }
            else
            {
                order.Side = MESSAGEFIX3Lib.FIXSideConstants.esFIXSideSell;
            }

            order.OrderType = sOrderType;
            order.TimeInForce = sTimeInForce;
            return SubmitNewOrder(order);
        }