Ejemplo n.º 1
0
        public void MarketOrderFillsAtBidAsk(OrderDirection direction)
        {
            var symbol = Symbol.Create("EURUSD", SecurityType.Forex, "fxcm");
            var exchangeHours = SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork);
            var quoteCash = new Cash("USD", 1000, 1);
            var symbolProperties = SymbolProperties.GetDefault("USD");
            var security = new Forex(symbol, exchangeHours, quoteCash, symbolProperties);

            var reference = DateTime.Now;
            var referenceUtc = reference.ConvertToUtc(TimeZones.NewYork);
            var timeKeeper = new TimeKeeper(referenceUtc);
            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));

            var brokerageModel = new FxcmBrokerageModel();
            var fillModel = brokerageModel.GetFillModel(security);

            const decimal bidPrice = 1.13739m;
            const decimal askPrice = 1.13746m;

            security.SetMarketPrice(new Tick(DateTime.Now, symbol, bidPrice, askPrice));

            var quantity = direction == OrderDirection.Buy ? 1 : -1;
            var order = new MarketOrder(symbol, quantity, DateTime.Now);
            var fill = fillModel.MarketFill(security, order);

            var expected = direction == OrderDirection.Buy ? askPrice : bidPrice;
            Assert.AreEqual(expected, fill.FillPrice);
        }
Ejemplo n.º 2
0
 public static Order Create(string property,OrderDirection direction)
 {
     Order order = new Order();
     order.Property = property;
     order.Direction = direction;
     return order;
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Sets the default order.
 /// </summary>
 /// <param name="options">The options.</param>
 /// <param name="column">The column.</param>
 /// <param name="direction">The direction.</param>
 public static void SetDefaultOrder(this DataOptions options, string column, OrderDirection direction = OrderDirection.Asc)
 {
     if (!options.Order.By.Any())
     {
         options.Order.Add(column, direction);
     }
 }
Ejemplo n.º 4
0
 /// <summary>
 /// 0/cancelOrder.php 
 /// </summary>
 public List<Order> cancelOrder(string oid, OrderDirection type)
 {
     try
     {
         string url = (this.baseURL) + "0/cancelOrder.php";
         string postData;
         int t = 0;
         switch (type)
         {
             case OrderDirection.bid:
                 t = 2;
                 break;
             case OrderDirection.ask:
                 t = 1;
                 break;
         }
         postData = "oid=" + oid + "&type=" + t;
         string responseStr = DoAuthenticatedAPIPost(url, apiKey, apiSecret, postData);
         var resp = JSON.Instance.ToObject<OrderResponseWithBalance>(responseStr);
         return resp.orders;
     }
     catch (Exception ex)
     {
         return null;
     }
 }
Ejemplo n.º 5
0
		public SearchOrder(PropertyType propertyToOrder, OrderDirection direction)
		{
			if (propertyToOrder == null)
				throw new ArgumentNullException("propertyToOrder");
			_propertyToOrder = new PropertyLiteral(propertyToOrder);
			_direction = direction;
		}
Ejemplo n.º 6
0
        /// <summary>
        /// Sets the columns ordering.
        /// </summary>
        /// <param name="orderNumber">The column's position on the ordering (multi-column ordering).</param>
        /// <param name="orderDirection">The column's sort direction.</param>
        /// <exception cref="System.ArgumentException">Thrown if the provided orderDirection is not valid.</exception>
        public void SetColumnOrdering(int orderNumber, string orderDirection)
        {
            this.OrderNumber = orderNumber;

            if (orderDirection.ToLower().Equals("asc")) this.SortDirection = Column.OrderDirection.Ascendant;
            else if (orderDirection.ToLower().Equals("desc")) this.SortDirection = Column.OrderDirection.Descendant;
            else throw new ArgumentException("The provided ordering direction was not valid. Valid values must be 'asc' or 'desc' only.");
        }
Ejemplo n.º 7
0
        public void AddColumn(string columnName, OrderDirection direction)
        {
            string temp = columnName + " " + direction.ToString().ToLower();

            if (!this.Columns.Contains(temp))
            {
                this.Columns.Add(temp);
            }
        }
Ejemplo n.º 8
0
        public RestAPIResponse Log(string id = null, int? page = null, int? perPage = null, OrderDirection? orderDirection = null)
        {
            //Contract.Requires<ArgumentException>((id != null) ? id.Trim().Length > 0 : true);
            //Contract.Requires<ArgumentException>((id != null) ? Constants.SUBSCRIPTION_ID_FORMAT.IsMatch(id) : true, Messages.INVALID_SUBSCRIPTION_ID);
            //Contract.Requires<ArgumentException>((page.HasValue) ? page.Value > 0 : true);
            //Contract.Requires<ArgumentException>((perPage.HasValue) ? perPage.Value > 0 : true);

            return _client.GetRequest().Request("push/log", new { id = id, page = page, perPage = perPage, order_dir = orderDirection });
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Order Constructor.
 /// </summary>
 /// <param name="id">Id of the parent order</param>
 /// <param name="symbol">Asset Symbol</param>
 /// <param name="status">Status of the order</param>
 /// <param name="direction">The direction of the order this event belongs to</param>
 /// <param name="fillPrice">Fill price information if applicable.</param>
 /// <param name="fillQuantity">Fill quantity</param>
 /// <param name="message">Message from the exchange</param>
 public OrderEvent(int id, string symbol, OrderStatus status, OrderDirection direction, decimal fillPrice, int fillQuantity, string message = "")
 {
     OrderId = id;
     Status = status;
     FillPrice = fillPrice;
     Message = message;
     FillQuantity = fillQuantity;
     Symbol = symbol;
     Direction = direction;
 }
Ejemplo n.º 10
0
        public Order(string orderColumn, OrderDirection direction = OrderDirection.Ascend)
        {
            if (string.IsNullOrEmpty(orderColumn))
            {
                throw new ArgumentNullException(MsgResource.ColumnNameRequired);
            }

            this.OrderColumn = orderColumn;
            this.OrderDirection = direction;
            this.OrderString = orderColumn + " " + GetDirectionString(direction);
        }
Ejemplo n.º 11
0
 private static string GetDirectionString(OrderDirection direction)
 {
     switch (direction)
     {
         case OrderDirection.Ascend: 
             return "ASC";
         case OrderDirection.Descend: 
             return "DESC";
         default: 
             return "ASC";
     }
 } 
Ejemplo n.º 12
0
        public RestAPIResponse Get(string id = null, string hash = null, string historicsId = null, int? page = null, int? perPage = null, OrderBy? orderBy = null, OrderDirection? orderDirection = null, bool? includeFinished = null)
        {
            //Contract.Requires<ArgumentException>((id != null) ? id.Trim().Length > 0 : true);
            //Contract.Requires<ArgumentException>((id != null) ? Constants.SUBSCRIPTION_ID_FORMAT.IsMatch(id) : true, Messages.INVALID_SUBSCRIPTION_ID);
            //Contract.Requires<ArgumentException>((hash != null) ? hash.Trim().Length > 0 : true);
            //Contract.Requires<ArgumentException>((hash != null) ? Constants.STREAM_HASH_FORMAT.IsMatch(hash) : true, Messages.INVALID_STREAM_HASH);
            //Contract.Requires<ArgumentException>((historicsId != null) ? historicsId.Trim().Length > 0 : true);
            //Contract.Requires<ArgumentException>((historicsId != null) ? Constants.HISTORICS_ID_FORMAT.IsMatch(historicsId) : true, Messages.INVALID_HISTORICS_ID);
            //Contract.Requires<ArgumentException>((page.HasValue) ? page.Value > 0 : true);
            //Contract.Requires<ArgumentException>((perPage.HasValue) ? perPage.Value > 0 : true);

            return _client.GetRequest().Request("push/get", new { id = id, hash = hash, historics_id = historicsId, page = page, per_page = perPage, order_by = orderBy, order_dir = orderDirection, include_finished = includeFinished });
        }
Ejemplo n.º 13
0
        public PagingAndSortingInfo(
            int page = 1,
            int pageSize = 10,
            string orderByField = "",
            OrderDirection orderDirection = OrderDirection.Ascending)
        {
            Condition.Requires(page).IsGreaterOrEqual(1);
            Condition.Requires(pageSize).IsGreaterOrEqual(1); ;

            this.Page = page;
            this.PageSize = pageSize;
            this.OrderByField = orderByField;
            this.OrderDirection = orderDirection;
        }
Ejemplo n.º 14
0
        public void Apply_DadoFiltroComOrderSorts_DeveRetornar(Restful.Query.Filter.Filters.Ordering.OrderByDirection sorts, OrderByDirection expected)
        {
            _filterStub
                .Setup(p => p.OrderBy)
                .Returns(new Restful.Query.Filter.Filters.Ordering.OrderBy(new List<Restful.Query.Filter.Filters.Ordering.Field>
                {
                    new Restful.Query.Filter.Filters.Ordering.Field("", sorts)
                }));

            var orderDirection = new OrderDirection();

            var actual = orderDirection.Apply(_filterStub.Object);

            actual.Should().Be(expected);
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OrderItem" /> class.
 /// </summary>
 /// <param name="field">The field.</param>
 /// <param name="direction">The order direction.</param>
 public OrderItem(string field, OrderDirection direction = OrderDirection.Asc)
 {
     Direction = direction;
     Field = field;
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 public Order()
 {
     ordDir    = OrderDirection.None;
     ordType   = OrderType.None;
     ordCond   = OrderCondition.None;
     ordStatus = OrderStatus.None;
     ordSender = OrderSender.None;
     ordOrigin = OrderOrigin.None;
     ordNote   = "Not Defined";
 }
 public new decimal GetMarginRemaining(SecurityPortfolioManager portfolio, Security security, OrderDirection direction)
 {
     return(base.GetMarginRemaining(portfolio, security, direction));
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Calculates the size of an entry order.
        /// </summary>
        private double AnalyseEntrySize(OrderDirection ordDir, ref PosDirection newPosDir)
        {
            double size = 0;
            PosDirection posDir = Data.PositionDirection;

            // Orders modification on a fly
            // Checks whether we are on the market
            if (posDir == PosDirection.Long || posDir == PosDirection.Short)
            {
                // We are on the market
                if (ordDir == OrderDirection.Buy && posDir == PosDirection.Long ||
                    ordDir == OrderDirection.Sell && posDir == PosDirection.Short)
                {
                    // In case of a Same Dir Signal
                    switch (Data.Strategy.SameSignalAction)
                    {
                        case SameDirSignalAction.Add:
                            if (Data.PositionLots + TradingSize(Data.Strategy.AddingLots) <
                                _maximumLots + Data.InstrProperties.LotStep/2)
                            {
                                // Adding
                                size = TradingSize(Data.Strategy.AddingLots);
                                newPosDir = posDir;
                            }
                            else
                            {
                                // Cancel the Adding
                                size = 0;
                                newPosDir = posDir;
                            }
                            break;
                        case SameDirSignalAction.Winner:
                            if (Data.PositionProfit > Epsilon &&
                                Data.PositionLots + TradingSize(Data.Strategy.AddingLots) <
                                _maximumLots + Data.InstrProperties.LotStep/2)
                            {
                                // Adding
                                size = TradingSize(Data.Strategy.AddingLots);
                                newPosDir = posDir;
                            }
                            else
                            {
                                // Cancel the Adding
                                size = 0;
                                newPosDir = posDir;
                            }
                            break;
                        case SameDirSignalAction.Nothing:
                            size = 0;
                            newPosDir = posDir;
                            break;
                    }
                }
                else if (ordDir == OrderDirection.Buy && posDir == PosDirection.Short ||
                         ordDir == OrderDirection.Sell && posDir == PosDirection.Long)
                {
                    // In case of an Opposite Dir Signal
                    switch (Data.Strategy.OppSignalAction)
                    {
                        case OppositeDirSignalAction.Reduce:
                            if (Data.PositionLots > TradingSize(Data.Strategy.ReducingLots))
                            {
                                // Reducing
                                size = TradingSize(Data.Strategy.ReducingLots);
                                newPosDir = posDir;
                            }
                            else
                            {
                                // Closing
                                size = Data.PositionLots;
                                newPosDir = PosDirection.Closed;
                            }
                            break;
                        case OppositeDirSignalAction.Close:
                            size = Data.PositionLots;
                            newPosDir = PosDirection.Closed;
                            break;
                        case OppositeDirSignalAction.Reverse:
                            size = Data.PositionLots + TradingSize(Data.Strategy.EntryLots);
                            newPosDir = posDir == PosDirection.Long ? PosDirection.Short : PosDirection.Long;
                            break;
                        case OppositeDirSignalAction.Nothing:
                            size = 0;
                            newPosDir = posDir;
                            break;
                    }
                }
            }
            else
            {
                // We are square on the market
                size = TradingSize(Data.Strategy.EntryLots);
                if (Data.Strategy.UseMartingale && Data.ConsecutiveLosses > 0)
                {
                    size = size * Math.Pow(Data.Strategy.MartingaleMultiplier, Data.ConsecutiveLosses);
                    size = NormalizeEntrySize(size);
                }
                size = Math.Min(size, _maximumLots);

                newPosDir = ordDir == OrderDirection.Buy ? PosDirection.Long : PosDirection.Short;
            }

            return size;
        }
Ejemplo n.º 19
0
 public DataTable QueryPageTable(string sqlstr, int pageNo, int pageSize, out int count, string @orderby,
                                 OrderDirection direction, string @select, params KeyValuePair <string, object>[] parameters)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 20
0
 public virtual SqlQuery GetSelectFirst(Expression <Func <TEntity, bool> > predicate,
                                        List <Expression <Func <TEntity, object> > > selectColumns, Expression <Func <TEntity, object> > orderColumn = null, OrderDirection direction = OrderDirection.Asc, params Expression <Func <TEntity, object> >[] includes)
 {
     return(GetSelect(predicate, true, selectColumns, orderColumn, direction, includes));
 }
Ejemplo n.º 21
0
 public DataTable QueryPageTableOffset(string sqlstr, int offset, int pageNo, int pageSize, string @orderby,
                                       OrderDirection direction = OrderDirection.DESC, string @select = "*", object parameters = null)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 22
0
 public Task <BuyResult> BuyAsync(ActivePair pair, int size, OrderDirection direction,
                                  DateTimeOffset expiration)
 {
     return(WsClient?.BuyAsync(pair, size, direction, expiration));
 }
Ejemplo n.º 23
0
        public static IDocumentQuery <T> OrderByMultipleItemsWithCommonOrder <T>(this IDocumentQuery <T> query, OrderDirection orderDirection, params string[] propertySelectors)
        {
            if (propertySelectors == null || !propertySelectors.Any())
            {
                return(query);
            }

            if (propertySelectors.Any(p => string.IsNullOrWhiteSpace(p)))
            {
                throw new ArgumentException("One or more property selectors is(are) invalid", nameof(propertySelectors));
            }

            query = orderDirection == OrderDirection.Asc
                ? query.OrderBy(propertySelectors)
                : query.OrderByDescending(propertySelectors);

            return(query);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Gets the margin cash available for a trade
        /// </summary>
        /// <param name="portfolio">The algorithm's portfolio</param>
        /// <param name="security">The security to be traded</param>
        /// <param name="direction">The direction of the trade</param>
        /// <returns>The margin available for the trade</returns>
        protected override decimal GetMarginRemaining(SecurityPortfolioManager portfolio, Security security, OrderDirection direction)
        {
            var holdings = security.Holdings;

            if (direction == OrderDirection.Hold)
            {
                return(portfolio.MarginRemaining);
            }

            //If the order is in the same direction as holdings, our remaining cash is our cash
            //In the opposite direction, our remaining cash is 2 x current value of assets + our cash
            if (holdings.IsLong)
            {
                switch (direction)
                {
                case OrderDirection.Buy:
                    return(portfolio.MarginRemaining);

                case OrderDirection.Sell:
                    return
                        // portion of margin to close the existing position
                        (GetMaintenanceMargin(security) +
                         // portion of margin to open the new position
                         security.Holdings.AbsoluteHoldingsValue * GetInitialMarginRequirement(security, security.Holdings.HoldingsValue) +
                         portfolio.MarginRemaining);
                }
            }
            else if (holdings.IsShort)
            {
                switch (direction)
                {
                case OrderDirection.Buy:
                    return
                        // portion of margin to close the existing position
                        (GetMaintenanceMargin(security) +
                         // portion of margin to open the new position
                         security.Holdings.AbsoluteHoldingsValue * GetInitialMarginRequirement(security, security.Holdings.HoldingsValue) +
                         portfolio.MarginRemaining);

                case OrderDirection.Sell:
                    return(portfolio.MarginRemaining);
                }
            }

            //No holdings, return cash
            return(portfolio.MarginRemaining);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Gets the margin available for trading a specific symbol in a specific direction.
        /// </summary>
        /// <param name="symbol">The symbol to compute margin remaining for</param>
        /// <param name="direction">The order/trading direction</param>
        /// <returns>The maximum order size that is currently executable in the specified direction</returns>
        public decimal GetMarginRemaining(Symbol symbol, OrderDirection direction = OrderDirection.Buy)
        {
            var security = Securities[symbol];

            return(security.MarginModel.GetMarginRemaining(this, security, direction));
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Get the minimum and maximum price for this security in the last bar
        /// Ignore the Trade/Quote distinction - fill with the latest pricing information
        /// </summary>
        /// <param name="asset">Security asset we're checking</param>
        /// <param name="direction">The order direction, decides whether to pick bid or ask</param>
        protected override Prices GetPrices(Security asset, OrderDirection direction)
        {
            var low     = asset.Low;
            var high    = asset.High;
            var open    = asset.Open;
            var close   = asset.Close;
            var current = asset.Price;
            var endTime = asset.Cache.GetData()?.EndTime ?? DateTime.MinValue;

            if (direction == OrderDirection.Hold)
            {
                return(new Prices(endTime, current, open, high, low, close));
            }

            // Only fill with data types we are subscribed to
            var subscriptionTypes = asset.Subscriptions.Select(x => x.Type).ToList();

            // Tick
            var tick = asset.Cache.GetData <Tick>();

            if (subscriptionTypes.Contains(typeof(Tick)) && tick != null)
            {
                var price = direction == OrderDirection.Sell ? tick.BidPrice : tick.AskPrice;
                if (price != 0m)
                {
                    return(new Prices(endTime, price, 0, 0, 0, 0));
                }

                // If the ask/bid spreads are not available for ticks, try the price
                price = tick.Price;
                if (price != 0m)
                {
                    return(new Prices(endTime, price, 0, 0, 0, 0));
                }
            }

            // Get both the last trade and last quote
            // Assume that the security has both a trade and quote subscription
            // This should be true for crypto securities
            var quoteBar = asset.Cache.GetData <QuoteBar>();

            if (quoteBar != null)
            {
                var tradeBar = asset.Cache.GetData <TradeBar>();

                if (tradeBar != null && tradeBar.EndTime > quoteBar.EndTime)
                {
                    // The latest pricing data came from a trade
                    return(new Prices(tradeBar));
                }
                else
                {
                    // The latest pricing data came from a quote
                    var bar = direction == OrderDirection.Sell ? quoteBar.Bid : quoteBar.Ask;
                    if (bar != null)
                    {
                        return(new Prices(quoteBar.EndTime, bar));
                    }
                }
            }

            return(new Prices(endTime, current, open, high, low, close));
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Gets the margin cash available for a trade
        /// </summary>
        /// <param name="portfolio">The algorithm's portfolio</param>
        /// <param name="security">The security to be traded</param>
        /// <param name="direction">The direction of the trade</param>
        /// <returns>The margin available for the trade</returns>
        public virtual decimal GetMarginRemaining(SecurityPortfolioManager portfolio, Security security, OrderDirection direction)
        {
            var holdings = security.Holdings;

            if (direction == OrderDirection.Hold)
            {
                return(portfolio.MarginRemaining);
            }

            //If the order is in the same direction as holdings, our remaining cash is our cash
            //In the opposite direction, our remaining cash is 2 x current value of assets + our cash
            if (holdings.IsLong)
            {
                switch (direction)
                {
                case OrderDirection.Buy:
                    return(portfolio.MarginRemaining);

                case OrderDirection.Sell:
                    return(security.MarginModel.GetMaintenanceMargin(security) * 2 + portfolio.MarginRemaining);
                }
            }
            else if (holdings.IsShort)
            {
                switch (direction)
                {
                case OrderDirection.Buy:
                    return(security.MarginModel.GetMaintenanceMargin(security) * 2 + portfolio.MarginRemaining);

                case OrderDirection.Sell:
                    return(portfolio.MarginRemaining);
                }
            }

            //No holdings, return cash
            return(portfolio.MarginRemaining);
        }
Ejemplo n.º 28
0
 public OrderField(string orderBy = "Id", OrderDirection orderDirection = Data.OrderDirection.Desc)
 {
     OrderBy        = orderBy;
     OrderDirection = orderDirection;
 }
Ejemplo n.º 29
0
 public Task <BinaryOptionsResult> BuyAsync(string requestId, ActivePair pair, decimal size, OrderDirection direction,
                                            DateTimeOffset expiration)
 {
     return(WsClient?.BuyAsync(requestId, pair, size, direction, expiration));
 }
Ejemplo n.º 30
0
 /// <summary>
 /// 初始化排序
 /// </summary>
 /// <param name="name">排序属性</param>
 /// <param name="direction">排序方向</param>
 public OrderByItem(string name, OrderDirection direction)
 {
     this.Name      = name;
     this.Direction = direction;
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Adds the order item to orderings list.
        /// </summary>
        /// <param name="field">The ordering field.</param>
        /// <param name="direction">The order direction.</param>
        public void Add(string field, OrderDirection direction = OrderDirection.Asc)
        {
            var filterItem = new OrderItem(field, direction);

            By.Add(filterItem);
        }
Ejemplo n.º 32
0
        /// <summary>
        ///     Sets order parameter on request.
        /// </summary>
        /// <param name="direction"></param>
        /// <returns></returns>
        public virtual T Order(OrderDirection direction)
        {
            _uriBuilder.SetQueryParam("order", direction.ToString().ToLower());

            return(this as T);
        }
 public IJobSearch Descending() {
     _OrderDirection = OrderDirection.Descending;
     return this;
 }
Ejemplo n.º 34
0
        public IMatchingEngineRoute FindRoute(string clientId, string tradingConditionId, string instrumentId, OrderDirection orderType)
        {
            var routes     = _routesCacheService.GetRoutes();
            var instrument = string.IsNullOrEmpty(instrumentId)
                ? null
                : _assetPairsCache.GetAssetPairById(instrumentId);

            var topRankRoutes = routes
                                .Where(r => EqualsOrAny(r.ClientId, clientId) &&
                                       EqualsOrAny(r.TradingConditionId, tradingConditionId) &&
                                       EqualsOrAny(r.Instrument, instrumentId) &&
                                       (!r.Type.HasValue || IsAny(r.Instrument) || r.Type.Value == orderType) &&
                                       IsAssetMatches(r.Asset, r.Type, instrument, orderType))
                                .GroupBy(r => r.Rank)
                                .OrderBy(gr => gr.Key)
                                .FirstOrDefault()?
                                .Select(gr => gr)
                                .ToArray();

            if (topRankRoutes == null)
            {
                return(null);
            }

            if (topRankRoutes.Length == 1)
            {
                return(topRankRoutes[0]);
            }

            var mostSpecificRoutes = topRankRoutes
                                     .GroupBy(GetSpecificationLevel)
                                     .OrderByDescending(gr => gr.Key)
                                     .First()
                                     .Select(gr => gr)
                                     .ToArray();

            if (mostSpecificRoutes.Length == 1)
            {
                return(mostSpecificRoutes[0]);
            }

            var highestPriorityRoutes = mostSpecificRoutes
                                        .GroupBy(GetSpecificationPriority)
                                        .OrderByDescending(gr => gr.Key)
                                        .First()
                                        .Select(gr => gr)
                                        .ToArray();

            if (highestPriorityRoutes.Length >= 1 &&
                highestPriorityRoutes.Select(r => r.MatchingEngineId).Distinct().Count() == 1)
            {
                return(highestPriorityRoutes[0]);
            }

            return(null);
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Validates limit/stopmarket order prices, pass security.Price for limit/stop if n/a
        /// </summary>
        private static bool IsValidOrderPrices(Security security, OrderType orderType, OrderDirection orderDirection, decimal stopPrice, decimal limitPrice, ref BrokerageMessageEvent message)
        {
            // validate order price
            var invalidPrice = orderType == OrderType.Limit && orderDirection == OrderDirection.Buy && limitPrice > security.Price ||
                orderType == OrderType.Limit && orderDirection == OrderDirection.Sell && limitPrice < security.Price ||
                orderType == OrderType.StopMarket && orderDirection == OrderDirection.Buy && stopPrice < security.Price ||
                orderType == OrderType.StopMarket && orderDirection == OrderDirection.Sell && stopPrice > security.Price;

            if (invalidPrice)
            {
                message = new BrokerageMessageEvent(BrokerageMessageType.Warning, "NotSupported",
                    "Limit Buy orders and Stop Sell orders must be below market, Limit Sell orders and Stop Buy orders must be above market."
                    );

                return false;
            }

            return true;
        }
Ejemplo n.º 36
0
        private static Func <IEnumerable <Thing>, IOrderedEnumerable <Thing> > OrderingFunc(Func <Thing, string> orderProperty, OrderDirection direction)
        {
            switch (direction)
            {
            case OrderDirection.Ascending:
                return(ts => ts.OrderBy(orderProperty));

            case OrderDirection.Descending:
                return(ts => ts.OrderByDescending(orderProperty));

            default:
                throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
            }
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Helper Constructor using Order to Initialize.
        /// </summary>
        /// <param name="order">Order for this order status</param>
        /// <param name="utcTime">Date/time of this event</param>
        /// <param name="orderFee">The order fee</param>
        /// <param name="message">Message from exchange or QC.</param>
        public OrderEvent(Order order, DateTime utcTime, decimal orderFee, string message = "") 
        {
            OrderId = order.Id;
            Symbol = order.Symbol;
            Status = order.Status;
            Direction = order.Direction;

            //Initialize to zero, manually set fill quantity
            FillQuantity = 0;
            FillPrice = 0;
            FillPriceCurrency = order.PriceCurrency;

            UtcTime = utcTime;
            OrderFee = Math.Abs(orderFee);
            Message = message;
        }
Ejemplo n.º 38
0
 public static OrderDirection GetOpositeDirection(this OrderDirection orderType)
 {
     return(orderType == OrderDirection.Buy ? OrderDirection.Sell : OrderDirection.Buy);
 }
Ejemplo n.º 39
0
 public static PositionDirection GetClosePositionDirection(this OrderDirection orderType)
 {
     return(orderType == OrderDirection.Buy ? PositionDirection.Short : PositionDirection.Long);
 }
Ejemplo n.º 40
0
 public static OrderDirection GetOrderDirectionToMatchInOrderBook(this OrderDirection orderType)
 {
     return(orderType.GetOpositeDirection());
 }
Ejemplo n.º 41
0
        public void GetOrderQueryString_ReturnsEmptyString_WhenInvalidField(PostFields postFields, OrderDirection orderDirection)
        {
            var input = new[]
            {
                Tuple.Create(postFields, orderDirection)
            }.ToList();

            var result = Ext.GetOrderQueryString(input);

            Assert.AreEqual("", result);
        }
Ejemplo n.º 42
0
 /// <summary>
 /// Gets the margin available for trading a specific symbol in a specific direction.
 /// Alias for <see cref="GetMarginRemaining(Symbol, OrderDirection)"/>
 /// </summary>
 /// <param name="symbol">The symbol to compute margin remaining for</param>
 /// <param name="direction">The order/trading direction</param>
 /// <returns>The maximum order size that is currently executable in the specified direction</returns>
 public decimal GetBuyingPower(Symbol symbol, OrderDirection direction = OrderDirection.Buy)
 {
     return(GetMarginRemaining(symbol, direction));
 }
Ejemplo n.º 43
0
 /// <summary>
 /// Order Event Constructor.
 /// </summary>
 /// <param name="orderId">Id of the parent order</param>
 /// <param name="symbol">Asset Symbol</param>
 /// <param name="utcTime">Date/time of this event</param>
 /// <param name="status">Status of the order</param>
 /// <param name="direction">The direction of the order this event belongs to</param>
 /// <param name="fillPrice">Fill price information if applicable.</param>
 /// <param name="fillQuantity">Fill quantity</param>
 /// <param name="orderFee">The order fee</param>
 /// <param name="message">Message from the exchange</param>
 public OrderEvent(int orderId, Symbol symbol, DateTime utcTime, OrderStatus status, OrderDirection direction, decimal fillPrice, int fillQuantity, decimal orderFee, string message = "")
 {
     OrderId = orderId;
     Symbol = symbol;
     UtcTime = utcTime;
     Status = status;
     Direction = direction;
     FillPrice = fillPrice;
     FillQuantity = fillQuantity;
     OrderFee = orderFee;
     Message = message;
 }
Ejemplo n.º 44
0
        /// <summary>
        /// ITimePeriod 항목들의 Duration 속성 값을 기준으로 정렬을 수행합니다.
        /// </summary>
        /// <param name="sortDir"></param>
        public virtual void SortByDuration(OrderDirection sortDir = OrderDirection.Asc) {
            var isAsc = (sortDir == OrderDirection.Asc);

            if(isAsc)
                _periods.Sort((lhs, rhs) => rhs.Duration.CompareTo(lhs.Duration));
            else
                _periods.Sort((lhs, rhs) => lhs.Duration.CompareTo(rhs.Duration));
        }
Ejemplo n.º 45
0
 /// <inheritdoc/>
 public Task <DigitalOptionsPlacedResult> PlaceDigitalOptions(string requestId, ActivePair pair, OrderDirection direction,
                                                              DigitalOptionsExpiryDuration duration, double amount)
 => WsClient?.PlaceDigitalOptions(requestId, pair, direction, duration, amount);
Ejemplo n.º 46
0
        private SqlQuery GetSelect(Expression <Func <TEntity, bool> > predicate, bool firstOnly,
                                   List <Expression <Func <TEntity, object> > > selectColumns, Expression <Func <TEntity, object> > orderColumn = null, OrderDirection direction = OrderDirection.Asc, params Expression <Func <TEntity, object> >[] includes)
        {
            var builder = InitBuilderSelect(firstOnly, selectColumns);

            if (includes.Any())
            {
                var joinsBuilder = AppendJoinToSelect(builder, includes);
                builder.Append(" FROM " + TableName);
                if (SqlConnector == ESqlConnector.Mssql)
                {
                    builder.Append(" (NOLOCK) ");
                }
                builder.Append(joinsBuilder);
            }
            else
            {
                builder.Append(" FROM " + TableName);
                if (SqlConnector == ESqlConnector.Mssql)
                {
                    builder.Append(" (NOLOCK) ");
                }
            }

            IDictionary <string, object> expando = new ExpandoObject();

            if (predicate != null)
            {
                // WHERE
                var queryProperties = new List <QueryParameter>();
                FillQueryProperties(ExpressionHelper.GetBinaryExpression(predicate.Body), ExpressionType.Default,
                                    ref queryProperties);

                builder.Append(" WHERE ");


                for (var i = 0; i < queryProperties.Count; i++)
                {
                    var item = queryProperties[i];
                    if (!string.IsNullOrEmpty(item.LinkingOperator) && i > 0)
                    {
                        builder.Append(string.Format("{0} {1}.{2} {3} {4} ", item.LinkingOperator, TableName,
                                                     item.PropertyName, item.QueryOperator, GetPropertyValue(item)));
                    }
                    else
                    {
                        builder.Append(string.Format("{0}.{1} {2} {3} ", TableName, item.PropertyName,
                                                     item.QueryOperator, GetPropertyValue(item)));
                    }

                    expando[item.PropertyName] = item.PropertyValue;
                }
            }

            if (orderColumn != null)
            {
                var orderProperties = GetPropertyInfos <TEntity>(orderColumn);
                if (orderProperties == null || !orderProperties.Any())
                {
                    throw new Exception("获取排序字段失败");
                }
                var orderProperty        = orderProperties.First();
                var orderColumnAttribute = orderProperty.GetCustomAttribute <ColumnAttribute>();
                var orderColumnName      = orderColumnAttribute == null ? orderProperty.Name: orderColumnAttribute.Name;

                builder.AppendFormat(" ORDER BY {0} {1}", orderColumnName, direction == OrderDirection.Asc ? "ASC" : "DESC");
            }

            if (firstOnly &&
                (SqlConnector == ESqlConnector.MySql ||
                 SqlConnector == ESqlConnector.PostgreSql))
            {
                builder.Append("LIMIT 1");
            }


            return(new SqlQuery(builder.ToString().TrimEnd(), expando));
        }
Ejemplo n.º 47
0
        /// <summary>
        /// ITimePeriod 항목들의 End 속성 값을 기준으로 정렬을 수행합니다.
        /// </summary>
        /// <param name="sortDir"></param>
        public virtual void SortByEnd(OrderDirection sortDir = OrderDirection.Asc) {
            var isAsc = sortDir == OrderDirection.Asc;

            if(isAsc)
                _periods.Sort((lhs, rhs) => rhs.End.CompareTo(lhs.End));
            else
                _periods.Sort((lhs, rhs) => lhs.End.CompareTo(rhs.End));
        }
Ejemplo n.º 48
0
 public DataTable QueryPageTable(string sqlstr, int pageNo, int pageSize, out int count, string @orderby,
                                 OrderDirection direction, string @select, object parameters = null)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 49
0
        /// <summary>
        /// 0/getOrders.php 
        /// </summary>
        public List<Order> getOrders(OrderDirection type, OrderStatus status, int oid = 0)
        {
            try
            {
                string url = (this.baseURL) + "0/getOrders.php";
                string postData = "";
                postData = "oid=" + oid;
                switch (type)
                {
                    case OrderDirection.bid:
                        postData += "&type=1";
                        break;
                    case OrderDirection.ask:
                        postData += "&type=2";
                        break;
                }
                switch (status)
                {
                    case OrderStatus.Active:
                        postData += "&status=1";
                        break;
                    case OrderStatus.NotSufficientFunds:
                        postData += "&status=2";
                        break;
                }
                string responseStr = DoAuthenticatedAPIPost(url, apiKey, apiSecret, postData);

                /*
                {  "usds":"0",
                 * "btcs":"0",
                 * "new_usds":{
                 *      "value":"0.00000",
                 *      "value_int":"0",
                 *      "display":"$0.00000",
                 *      "display_short":"$0.00",
                 *      "currency":"USD"},
                 *  "new_btcs":{
                 *      "value":"0.00000000",
                 *      "value_int":"0",
                 *      "display":"0.00000000\u00a0BTC",
                 *      "display_short":"0.00\u00a0BTC",
                 *      "currency":"BTC"},
                 *   "orders":[{"oid":"07dfa77e-eedb-4d68-bc77-55280a909cda","currency":"USD","item":"BTC","type":2,"amount":"1.00000000","amount_int":"100000000","price":"6.19990","price_int":"619990","status":0,"real_status":"invalid","dark":0,"date":1325782840,"priority":"1325782840517162"},{"oid":"205fc95a-89f0-4ebb-becf-43032deca20d","currency":"USD","item":"BTC","type":2,"amount":"1.00000000","amount_int":"100000000","price":"5.53808","price_int":"553808","status":0,"real_status":"invalid","dark":0,"date":1325712373,"priority":"1325712373261098"},{"oid":"429d5929-dba1-4f95-af68-dd3b131e5956","currency":"USD","item":"BTC","type":2,"amount":"2.00000000","amount_int":"200000000","price":"6.70970","price_int":"670970","status":0,"real_status":"invalid","dark":0,"date":1325886640,"priority":"1325886640581576"},{"oid":"5897bfd6-6fdf-4e03-80d8-75ce254186f8","currency":"USD","item":"BTC","type":2,"amount":"1000.00000000","amount_int":"100000000000","price":"10.00000","price_int":"1000000","status":0,"real_status":"invalid","dark":0,"date":1344979233,"priority":"1344979233573133"},{"oid":"65bc20e6-0ec7-48be-81e3-b5a8a59fc86f","currency":"USD","item":"BTC","type":2,"amount":"0.29860000","amount_int":"29860000","price":"6.63000","price_int":"663000","status":0,"real_status":"invalid","dark":0,"date":1325885130,"priority":"1325885130360685"},{"oid":"7a10f3c0-dab3-4817-9a32-b6f3f2b9d0d2","currency":"USD","item":"BTC","type":2,"amount":"1000.00000000","amount_int":"100000000000","price":"10.00000","price_int":"1000000","status":0,"real_status":"invalid","dark":0,"date":1344981405,"priority":"1344981405037818"},{"oid":"b87ceee1-04c5-4d91-a94e-54ee1d221411","currency":"USD","item":"BTC","type":2,"amount":"0.14900000","amount_int":"14900000","price":"6.70970","price_int":"670970","status":0,"real_status":"invalid","dark":0,"date":1325886436,"priority":"1325886436583107"},{"oid":"c533db7c-c972-429e-8084-ef0bbb09c1c9","currency":"USD","item":"BTC","type":2,"amount":"0.29860000","amount_int":"29860000","price":"6.63000","price_int":"663000","status":0,"real_status":"invalid","dark":0,"date":1325885128,"priority":"1325885128171198"},{"oid":"df55f311-f675-4b11-8fcc-f2a8061d21bb","currency":"USD","item":"BTC","type":2,"amount":"1000.00000000","amount_int":"100000000000","price":"10.00000","price_int":"1000000","status":0,"real_status":"invalid","dark":0,"date":1344979257,"priority":"1344979257804781"},{"oid":"e1e40c79-aeef-4f0c-affc-1e415cfb402c","currency":"USD","item":"BTC","type":2,"amount":"1000.00000000","amount_int":"100000000000","price":"10.00000","price_int":"1000000","status":0,"real_status":"invalid","dark":0,"date":1344979054,"priority":"1344979054815263"},{"oid":"f597c8fa-2a17-4db0-9695-71a2394c748f","currency":"USD","item":"BTC","type":2,"amount":"1.00000000","amount_int":"100000000","price":"6.19990","price_int":"619990","status":0,"real_status":"invalid","dark":0,"date":1325782848,"priority":"1325782848803275"},{"oid":"f92614b2-ecc7-470f-9f36-01bb19c65796","currency":"USD","item":"BTC","type":2,"amount":"0.29860000","amount_int":"29860000","price":"6.63000","price_int":"663000","status":0,"real_status":"invalid","dark":0,"date":1325885120,"priority":"1325885120229746"}]}
                 */
                var resp = JSON.Instance.ToObject<OrderResponseWithBalance>(responseStr);
                return resp.orders;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
Ejemplo n.º 50
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="attribute">The key of the attribute that is used for sorting</param>
 /// <param name="direction">The sort direction</param>
 /// <param name="entity">The entity that is used for sorting</param>
 public Order(ushort attribute, OrderDirection direction, Entity entity)
 {
     Attribute = attribute;
     Direction = direction;
     Entity    = entity;
 }
Ejemplo n.º 51
0
 /// <summary>
 /// 初始化排序项
 /// </summary>
 /// <param name="name">排序属性</param>
 /// <param name="direction">排序方向</param>
 public OrderByItem( string name, OrderDirection direction ) {
     Name = name;
     Direction = direction;
 }
Ejemplo n.º 52
0
        /// <summary>
        /// Validates limit/stopmarket order prices, pass security.Price for limit/stop if n/a
        /// </summary>
        private static bool IsValidOrderPrices(Security security, OrderType orderType, OrderDirection orderDirection, decimal stopPrice, decimal limitPrice, ref BrokerageMessageEvent message)
        {
            // validate order price
            var invalidPrice = orderType == OrderType.Limit && orderDirection == OrderDirection.Buy && limitPrice > security.Price ||
                               orderType == OrderType.Limit && orderDirection == OrderDirection.Sell && limitPrice < security.Price ||
                               orderType == OrderType.StopMarket && orderDirection == OrderDirection.Buy && stopPrice <security.Price ||
                                                                                                                       orderType == OrderType.StopMarket && orderDirection == OrderDirection.Sell && stopPrice> security.Price;

            if (invalidPrice)
            {
                message = new BrokerageMessageEvent(BrokerageMessageType.Warning, "NotSupported",
                                                    "Limit Buy orders and Stop Sell orders must be below market, Limit Sell orders and Stop Buy orders must be above market."
                                                    );

                return(false);
            }

            return(true);
        }
Ejemplo n.º 53
0
        /// <summary>
        /// Get the minimum and maximum price for this security in the last bar:
        /// </summary>
        /// <param name="asset">Security asset we're checking</param>
        /// <param name="minimumPrice">Minimum price in the last data bar</param>
        /// <param name="maximumPrice">Minimum price in the last data bar</param>
        /// <param name="direction">The order direction, decides whether to pick bid or ask</param>
        public virtual void DataMinMaxPrices(Security asset, out decimal minimumPrice, out decimal maximumPrice, OrderDirection direction)
        {
            var tick = asset.Cache.GetData<Tick>();
            if (tick != null)
            {
                var price = tick.Value;
                if (direction == OrderDirection.Sell && tick.BidPrice != 0)
                {
                    price = tick.BidPrice;
                }
                else if (direction == OrderDirection.Buy && tick.AskPrice != 0)
                {
                    price = tick.AskPrice;
                }
                minimumPrice = maximumPrice = price;
                return;
            }

            var quoteBar = asset.Cache.GetData<QuoteBar>();
            if (quoteBar != null)
            {
                var bar = direction == OrderDirection.Sell ? quoteBar.Ask : quoteBar.Bid;
                minimumPrice = quoteBar.Low;
                maximumPrice = quoteBar.High;
                if (bar != null)
                {
                    if (bar.High != 0) maximumPrice = bar.High;
                    if (bar.Low != 0) minimumPrice = bar.Low;
                }
                return;
            }

            var tradeBar = asset.Cache.GetData<TradeBar>();
            if (tradeBar != null)
            {
                minimumPrice = tradeBar.Low;
                maximumPrice = tradeBar.High;
                return;
            }

            var lastData = asset.GetLastData();
            var lastBar = lastData as IBar;
            if (lastBar != null)
            {
                minimumPrice = lastBar.Low;
                maximumPrice = lastBar.High;
                return;
            }

            minimumPrice = maximumPrice = asset.Price;
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Validates limit/stopmarket order prices, pass security.Price for limit/stop if n/a
        /// </summary>
        private static bool IsValidOrderPrices(Security security, OrderType orderType, OrderDirection orderDirection, decimal stopPrice, decimal limitPrice, ref BrokerageMessageEvent message)
        {
            // validate order price
            var invalidPrice = orderType == OrderType.Limit && orderDirection == OrderDirection.Buy && limitPrice > security.Price ||
                               orderType == OrderType.Limit && orderDirection == OrderDirection.Sell && limitPrice < security.Price ||
                               orderType == OrderType.StopMarket && orderDirection == OrderDirection.Buy && stopPrice <security.Price ||
                                                                                                                       orderType == OrderType.StopMarket && orderDirection == OrderDirection.Sell && stopPrice> security.Price;

            if (invalidPrice)
            {
                message = new BrokerageMessageEvent(BrokerageMessageType.Warning, "NotSupported",
                                                    "Limit Buy orders and Stop Sell orders must be below market, Limit Sell orders and Stop Buy orders must be above market."
                                                    );

                return(false);
            }

            // Validate FXCM maximum distance for limit and stop orders:
            // there are two different Max Limits, 15000 pips and 50% rule,
            // whichever comes first (for most pairs, 50% rule comes first)
            var maxDistance = Math.Min(
                // MinimumPriceVariation is 1/10th of a pip
                security.SymbolProperties.MinimumPriceVariation * 10 * 15000,
                security.Price / 2);
            var currentPrice = security.Price;
            var minPrice     = currentPrice - maxDistance;
            var maxPrice     = currentPrice + maxDistance;

            var outOfRangePrice = orderType == OrderType.Limit && orderDirection == OrderDirection.Buy && limitPrice <minPrice ||
                                                                                                                      orderType == OrderType.Limit && orderDirection == OrderDirection.Sell && limitPrice> maxPrice ||
                                  orderType == OrderType.StopMarket && orderDirection == OrderDirection.Buy && stopPrice > maxPrice ||
                                  orderType == OrderType.StopMarket && orderDirection == OrderDirection.Sell && stopPrice < minPrice;

            if (outOfRangePrice)
            {
                var orderPrice = orderType == OrderType.Limit ? limitPrice : stopPrice;

                message = new BrokerageMessageEvent(BrokerageMessageType.Warning, "NotSupported",
                                                    $"The {orderType} {orderDirection} order price ({orderPrice}) is too far from the current market price ({currentPrice})."
                                                    );

                return(false);
            }

            return(true);
        }
Ejemplo n.º 55
0
 /// <summary>
 /// Maps OrderDirection enumeration
 /// </summary>
 private IB.ActionSide ConvertOrderDirection(OrderDirection direction)
 {
     switch (direction)
     {
         case OrderDirection.Buy:  return IB.ActionSide.Buy;
         case OrderDirection.Sell: return IB.ActionSide.Sell;
         case OrderDirection.Hold: return IB.ActionSide.Undefined;
         default:
             throw new InvalidEnumArgumentException("direction", (int) direction, typeof (OrderDirection));
     }
 }
Ejemplo n.º 56
0
        /// <summary>
        /// Gets the margin cash available for a trade
        /// </summary>
        /// <param name="portfolio">The algorithm's portfolio</param>
        /// <param name="security">The security to be traded</param>
        /// <param name="direction">The direction of the trade</param>
        /// <returns>The margin available for the trade</returns>
        public virtual decimal GetMarginRemaining(SecurityPortfolioManager portfolio, Security security, OrderDirection direction)
        {
            var holdings = security.Holdings;

            if (direction == OrderDirection.Hold)
            {
                return portfolio.MarginRemaining;
            }

            //If the order is in the same direction as holdings, our remaining cash is our cash
            //In the opposite direction, our remaining cash is 2 x current value of assets + our cash
            if (holdings.IsLong)
            {
                switch (direction)
                {
                    case OrderDirection.Buy:
                        return portfolio.MarginRemaining;
                    case OrderDirection.Sell:
                        return security.MarginModel.GetMaintenanceMargin(security)*2 + portfolio.MarginRemaining;
                }
            }
            else if (holdings.IsShort)
            {
                switch (direction)
                {
                    case OrderDirection.Buy:
                        return security.MarginModel.GetMaintenanceMargin(security)*2 + portfolio.MarginRemaining;
                    case OrderDirection.Sell:
                        return portfolio.MarginRemaining;
                }
            }

            //No holdings, return cash
            return portfolio.MarginRemaining;
        }
        /// <summary>
        /// Given the name of a property on the entity and an order this will create the appropriate
        /// IQueryable to sort on that property.
        /// </summary>
        /// <typeparam name="TEntity">The entity type.</typeparam>
        /// <param name="source">The source query.</param>
        /// <param name="orderByProperty">The property to order by, must exist in TEntity or an exception will be thrown.</param>
        /// <param name="direction">The direction to order results by.</param>
        /// <remarks>
        /// Originally written by user Icarus
        /// https://stackoverflow.com/questions/7265186/how-do-i-specify-the-linq-orderby-argument-dynamically
        /// </remarks>
        /// <returns>A new query ordered by the given property.</returns>
        public static IQueryable <TEntity> OrderByProperty <TEntity>(this IQueryable <TEntity> source, string orderByProperty, OrderDirection direction)
        {
            string command           = direction == OrderDirection.Ascending ? "OrderBy" : "OrderByDescending";
            var    type              = typeof(TEntity);
            var    property          = type.GetProperty(orderByProperty);
            var    parameter         = Expression.Parameter(type, "p");
            var    propertyAccess    = Expression.MakeMemberAccess(parameter, property);
            var    orderByExpression = Expression.Lambda(propertyAccess, parameter);
            var    resultExpression  = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExpression));

            return(source.Provider.CreateQuery <TEntity>(resultExpression));
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Gets the margin cash available for a trade
        /// </summary>
        /// <param name="portfolio">The algorithm's portfolio</param>
        /// <param name="security">The security to be traded</param>
        /// <param name="direction">The direction of the trade</param>
        /// <returns>The margin available for the trade</returns>
        protected override decimal GetMarginRemaining(SecurityPortfolioManager portfolio, Security security, OrderDirection direction)
        {
            var result = portfolio.MarginRemaining;

            if (direction != OrderDirection.Hold)
            {
                var holdings = security.Holdings;
                //If the order is in the same direction as holdings, our remaining cash is our cash
                //In the opposite direction, our remaining cash is 2 x current value of assets + our cash
                if (holdings.IsLong)
                {
                    switch (direction)
                    {
                    case OrderDirection.Sell:
                        result +=
                            // portion of margin to close the existing position
                            GetMaintenanceMargin(security) +
                            // portion of margin to open the new position
                            security.Holdings.AbsoluteHoldingsValue * GetInitialMarginRequirement(security, security.Holdings.HoldingsValue);
                        break;
                    }
                }
                else if (holdings.IsShort)
                {
                    switch (direction)
                    {
                    case OrderDirection.Buy:
                        result +=
                            // portion of margin to close the existing position
                            GetMaintenanceMargin(security) +
                            // portion of margin to open the new position
                            security.Holdings.AbsoluteHoldingsValue * GetInitialMarginRequirement(security, security.Holdings.HoldingsValue);
                        break;
                    }
                }
            }

            result -= portfolio.TotalPortfolioValue * RequiredFreeBuyingPowerPercent;
            return(result < 0 ? 0 : result);
        }
Ejemplo n.º 59
0
 public static Order CreateOrder(string orderColumn, OrderDirection direction)
 {
     return new Order(orderColumn, direction); 
 }
 protected override Prices GetPrices(Security asset, OrderDirection direction)
 {
     GetPricesWasCalled = true;
     return(new Prices(orderDateTime, 12345, 12345, 12345, 12345, 12345));
 }