当前位置: 首页>>代码示例>>C#>>正文


C# IBrokerage类代码示例

本文整理汇总了C#中IBrokerage的典型用法代码示例。如果您正苦于以下问题:C# IBrokerage类的具体用法?C# IBrokerage怎么用?C# IBrokerage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


IBrokerage类属于命名空间,在下文中一共展示了IBrokerage类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: DisposeBrokerage

 protected override void DisposeBrokerage(IBrokerage brokerage)
 {
     if (!_manualGatewayControl && brokerage != null)
     {
         brokerage.Disconnect();
     }
 }
开发者ID:skyfyl,项目名称:Lean,代码行数:7,代码来源:InteractiveBrokersOrderTests.cs

示例2: ModifyOrderToFill

        public override bool ModifyOrderToFill(IBrokerage brokerage, Order order, decimal lastMarketPrice)
        {
            // FXCM Buy Limit orders will be rejected if the limit price is above the market price
            // FXCM Sell Limit orders will be rejected if the limit price is below the market price

            var limit = (LimitOrder)order;
            var previousLimit = limit.LimitPrice;

            var fxcmBrokerage = (FxcmBrokerage)brokerage;
            var quotes = fxcmBrokerage.GetBidAndAsk(new List<string> { new FxcmSymbolMapper().GetBrokerageSymbol(order.Symbol) });

            if (order.Quantity > 0)
            {
                // for limit buys we need to increase the limit price
                // buy limit price must be at bid price or below
                var bidPrice = Convert.ToDecimal(quotes.Single().BidPrice);
                Log.Trace("FxcmLimitOrderTestParameters.ModifyOrderToFill(): Bid: " + bidPrice);
                limit.LimitPrice = Math.Max(previousLimit, Math.Min(bidPrice, limit.LimitPrice * 2));
            }
            else
            {
                // for limit sells we need to decrease the limit price
                // sell limit price must be at ask price or above
                var askPrice = Convert.ToDecimal(quotes.Single().AskPrice);
                Log.Trace("FxcmLimitOrderTestParameters.ModifyOrderToFill(): Ask: " + askPrice);
                limit.LimitPrice = Math.Min(previousLimit, Math.Max(askPrice, limit.LimitPrice / 2));
            }

            return limit.LimitPrice != previousLimit;
        }
开发者ID:skyfyl,项目名称:Lean,代码行数:30,代码来源:FxcmLimitOrderTestParameters.cs

示例3: DisposeBrokerage

 protected override void DisposeBrokerage(IBrokerage brokerage)
 {
     if (brokerage != null)
     {
         brokerage.Disconnect();
     }
 }
开发者ID:reddream,项目名称:Lean,代码行数:7,代码来源:InteractiveBrokersOrderTests.cs

示例4: ModifyOrderToFill

        public override bool ModifyOrderToFill(IBrokerage brokerage, Order order, decimal lastMarketPrice)
        {
            // FXCM Buy StopMarket orders will be rejected if the stop price is below the market price
            // FXCM Sell StopMarket orders will be rejected if the stop price is above the market price

            var stop = (StopMarketOrder)order;
            var previousStop = stop.StopPrice;

            var fxcmBrokerage = (FxcmBrokerage)brokerage;
            var quotes = fxcmBrokerage.GetBidAndAsk(new List<string> { new FxcmSymbolMapper().GetBrokerageSymbol(order.Symbol) });
            
            if (order.Quantity > 0)
            {
                // for stop buys we need to decrease the stop price
                // buy stop price must be strictly above ask price
                var askPrice = Convert.ToDecimal(quotes.Single().AskPrice);
                Log.Trace("FxcmStopMarketOrderTestParameters.ModifyOrderToFill(): Ask: " + askPrice);
                stop.StopPrice = Math.Min(previousStop, Math.Max(askPrice, stop.StopPrice / 2) + 0.00001m);
            }
            else
            {
                // for stop sells we need to increase the stop price
                // sell stop price must be strictly below bid price
                var bidPrice = Convert.ToDecimal(quotes.Single().BidPrice);
                Log.Trace("FxcmStopMarketOrderTestParameters.ModifyOrderToFill(): Bid: " + bidPrice);
                stop.StopPrice = Math.Max(previousStop, Math.Min(bidPrice, stop.StopPrice * 2) - 0.00001m);
            }

            return stop.StopPrice != previousStop;
        }
开发者ID:skyfyl,项目名称:Lean,代码行数:30,代码来源:FxcmStopMarketOrderTestParameters.cs

示例5: ModifyOrderToFill

        public override bool ModifyOrderToFill(IBrokerage brokerage, Order order, decimal lastMarketPrice)
        {
            var stop = (StopLimitOrder) order;
            var previousStop = stop.StopPrice;
            if (order.Quantity > 0)
            {
                // for stop buys we need to decrease the stop price
                stop.StopPrice = Math.Min(stop.StopPrice, Math.Max(stop.StopPrice/2, Math.Round(lastMarketPrice, 2, MidpointRounding.AwayFromZero)));
                
                //change behaviour for forex type unit tests
                if(order.SecurityType == SecurityType.Forex)
                {
                    stop.StopPrice = Math.Min(stop.StopPrice, Math.Max(stop.StopPrice / 2, Math.Round(lastMarketPrice, 4, MidpointRounding.AwayFromZero)));
                }
            }
            else
            {
                // for stop sells we need to increase the stop price
                stop.StopPrice = Math.Max(stop.StopPrice, Math.Min(stop.StopPrice * 2, Math.Round(lastMarketPrice, 2, MidpointRounding.AwayFromZero)));


                //change behaviour for forex type unit tests
                if (order.SecurityType == SecurityType.Forex)
                {
                    stop.StopPrice = Math.Max(stop.StopPrice, Math.Min(stop.StopPrice * 2, Math.Round(lastMarketPrice, 4, MidpointRounding.AwayFromZero)));
                }
            }
            stop.LimitPrice = stop.StopPrice;
            return stop.StopPrice != previousStop;
        }
开发者ID:skyfyl,项目名称:Lean,代码行数:30,代码来源:StopLimitOrderTestParameters.cs

示例6: LiveTradingRealTimeHandler

 /********************************************************
 * PUBLIC CONSTRUCTOR
 *********************************************************/
 /// <summary>
 /// Initialize the realtime event handler with all information required for triggering daily events.
 /// </summary>
 public LiveTradingRealTimeHandler(IAlgorithm algorithm, IDataFeed feed, IResultHandler results, IBrokerage brokerage, AlgorithmNodePacket job)
 {
     //Initialize:
     _algorithm = algorithm;
     _events = new List<RealTimeEvent>();
     _today = new Dictionary<SecurityType, MarketToday>();
     _feed = feed;
     _results = results;
 }
开发者ID:intelliBrain,项目名称:Lean,代码行数:15,代码来源:LiveTradingRealTimeHandler.cs

示例7: Initialize

        /// <summary>
        /// Creates a new BacktestingTransactionHandler using the BacktestingBrokerage
        /// </summary>
        /// <param name="algorithm">The algorithm instance</param>
        /// <param name="brokerage">The BacktestingBrokerage</param>
        /// <param name="resultHandler"></param>
        public override void Initialize(IAlgorithm algorithm, IBrokerage brokerage, IResultHandler resultHandler)
        {
            if (!(brokerage is BacktestingBrokerage))
            {
                throw new ArgumentException("Brokerage must be of type BacktestingBrokerage for use wth the BacktestingTransactionHandler");
            }
            
            _brokerage = (BacktestingBrokerage) brokerage;

            base.Initialize(algorithm, brokerage, resultHandler);
        }
开发者ID:skyfyl,项目名称:Lean,代码行数:17,代码来源:BacktestingTransactionHandler.cs

示例8: BrokerageTransactionHandler

        /// <summary>
        /// Creates a new BrokerageTransactionHandler to process orders using the specified brokerage implementation
        /// </summary>
        /// <param name="algorithm">The algorithm instance</param>
        /// <param name="brokerage">The brokerage implementation to process orders and fire fill events</param>
        public BrokerageTransactionHandler(IAlgorithm algorithm, IBrokerage brokerage)
        {
            if (brokerage == null)
            {
                throw new ArgumentNullException("brokerage");
            }

            _brokerage = brokerage;
            _brokerage.OrderEvent += (sender, fill) =>
            {
                // save that the order event took place, we're initializing the list with a capacity of 2 to reduce number of mallocs
                //these hog memory
                //List<OrderEvent> orderEvents = _orderEvents.GetOrAdd(orderEvent.OrderId, i => new List<OrderEvent>(2));
                //orderEvents.Add(orderEvent);

                //Apply the filled order to our portfolio:
                if (fill.Status == OrderStatus.Filled || fill.Status == OrderStatus.PartiallyFilled)
                {
                    _algorithm.Portfolio.ProcessFill(fill);
                }

                //We have an event! :) Order filled, send it in to be handled by algorithm portfolio.
                if (fill.Status != OrderStatus.None) //order.Status != OrderStatus.Submitted
                {
                    //Create new order event:
                    Engine.ResultHandler.OrderEvent(fill);
                    try
                    {
                        //Trigger our order event handler
                        _algorithm.OnOrderEvent(fill);
                    }
                    catch (Exception err)
                    {
                        _algorithm.Error("Order Event Handler Error: " + err.Message);
                    }
                }
            };

            //_brokerage.AccountChanged +=
            //_brokerage.PortfolioChanged +=

            IsActive = true;

            _algorithm = algorithm;

            // also save off the various order data structures locally
            _orders = algorithm.Transactions.Orders;
            _orderEvents = algorithm.Transactions.OrderEvents;
            _orderQueue = algorithm.Transactions.OrderQueue;
        }
开发者ID:intelliBrain,项目名称:Lean,代码行数:55,代码来源:BrokerageTransactionHandler.cs

示例9: ModifyOrderToFill

 public override bool ModifyOrderToFill(IBrokerage brokerage, Order order, decimal lastMarketPrice)
 {
     var stop = (StopMarketOrder)order;
     var previousStop = stop.StopPrice;
     if (order.Quantity > 0)
     {
         // for stop buys we need to decrease the stop price
         stop.StopPrice = Math.Min(stop.StopPrice, Math.Max(stop.StopPrice / 2, lastMarketPrice));
     }
     else
     {
         // for stop sells we need to increase the stop price
         stop.StopPrice = Math.Max(stop.StopPrice, Math.Min(stop.StopPrice * 2, lastMarketPrice));
     }
     return stop.StopPrice != previousStop;
 }
开发者ID:hittudiv,项目名称:Lean,代码行数:16,代码来源:StopMarketOrderTestParameters.cs

示例10: ModifyOrderToFill

        public override bool ModifyOrderToFill(IBrokerage brokerage, Order order, decimal lastMarketPrice)
        {
            // limit orders will process even if they go beyond the market price

            var limit = (LimitOrder) order;
            if (order.Quantity > 0)
            {
                // for limit buys we need to increase the limit price
                limit.LimitPrice *= 2;
            }
            else
            {
                // for limit sells we need to decrease the limit price
                limit.LimitPrice /= 2;
            }
            return true;
        }
开发者ID:hittudiv,项目名称:Lean,代码行数:17,代码来源:LimitOrderTestParameters.cs

示例11: BrokerageTransactionHandler

        /// <summary>
        /// Creates a new BrokerageTransactionHandler to process orders using the specified brokerage implementation
        /// </summary>
        /// <param name="algorithm">The algorithm instance</param>
        /// <param name="brokerage">The brokerage implementation to process orders and fire fill events</param>
        public BrokerageTransactionHandler(IAlgorithm algorithm, IBrokerage brokerage)
        {
            if (brokerage == null)
            {
                throw new ArgumentNullException("brokerage");
            }

            // we don't need to do this today because we just initialized/synced
            _syncedLiveBrokerageCashToday = true;
            _lastSyncTimeTicks = DateTime.Now.Ticks;

            _brokerage = brokerage;
            _brokerage.OrderStatusChanged += (sender, fill) =>
            {
                HandleOrderEvent(fill);
            };

            _brokerage.SecurityHoldingUpdated += (sender, holding) =>
            {
                HandleSecurityHoldingUpdated(holding);
            };

            _brokerage.AccountChanged += (sender, account) =>
            {
                HandleAccountChanged(account);
            };

            IsActive = true;

            _algorithm = algorithm;

            // also save off the various order data structures locally
            _orders = algorithm.Transactions.Orders;
            _orderEvents = algorithm.Transactions.OrderEvents;
            _orderQueue = algorithm.Transactions.OrderQueue;
        }
开发者ID:sopnic,项目名称:Lean,代码行数:41,代码来源:BrokerageTransactionHandler.cs

示例12: Setup

        /// <summary>
        /// Primary entry point to setup a new algorithm
        /// </summary>
        /// <param name="algorithm">Algorithm instance</param>
        /// <param name="brokerage">New brokerage output instance</param>
        /// <param name="job">Algorithm job task</param>
        /// <param name="resultHandler">The configured result handler</param>
        /// <param name="transactionHandler">The configurated transaction handler</param>
        /// <param name="realTimeHandler">The configured real time handler</param>
        /// <returns>True on successfully setting up the algorithm state, or false on error.</returns>
        public bool Setup(IAlgorithm algorithm, out IBrokerage brokerage, AlgorithmNodePacket job, IResultHandler resultHandler, ITransactionHandler transactionHandler, IRealTimeHandler realTimeHandler)
        {
            _algorithm = algorithm;
            brokerage = default(IBrokerage);

            // verify we were given the correct job packet type
            var liveJob = job as LiveNodePacket;
            if (liveJob == null)
            {
                AddInitializationError("BrokerageSetupHandler requires a LiveNodePacket");
                return false;
            }

            // verify the brokerage was specified
            if (string.IsNullOrWhiteSpace(liveJob.Brokerage))
            {
                AddInitializationError("A brokerage must be specified");
                return false;
            }

            // attach to the message event to relay brokerage specific initialization messages
            EventHandler<BrokerageMessageEvent> brokerageOnMessage = (sender, args) =>
            {
                if (args.Type == BrokerageMessageType.Error)
                {
                    AddInitializationError(string.Format("Brokerage Error Code: {0} - {1}", args.Code, args.Message));
                }
            };

            try
            {
                Log.Trace("BrokerageSetupHandler.Setup(): Initializing algorithm...");

                //Execute the initialize code:
                var isolator = new Isolator();
                var initializeComplete = isolator.ExecuteWithTimeLimit(TimeSpan.FromSeconds(10), () =>
                {
                    try
                    {
                        //Set the live trading level asset/ram allocation limits.
                        //Protects algorithm from linux killing the job by excess memory:
                        switch (job.ServerType)
                        {
                            case ServerType.Server1024:
                                algorithm.SetAssetLimits(100, 20, 10);
                                break;

                            case ServerType.Server2048:
                                algorithm.SetAssetLimits(400, 50, 30);
                                break;

                            default: //512
                                algorithm.SetAssetLimits(50, 25, 15);
                                break;
                        }

                        //Algorithm is live, not backtesting:
                        algorithm.SetLiveMode(true);
                        //Initialize the algorithm's starting date
                        algorithm.SetDateTime(DateTime.UtcNow);
                        //Set the source impl for the event scheduling
                        algorithm.Schedule.SetEventSchedule(realTimeHandler);
                        //Initialise the algorithm, get the required data:
                        algorithm.Initialize();
                    }
                    catch (Exception err)
                    {
                        AddInitializationError(err.Message);
                    }
                });

                if (!initializeComplete)
                {
                    AddInitializationError("Initialization timed out.");
                    return false;
                }
                try
                {
                    // find the correct brokerage factory based on the specified brokerage in the live job packet
                    _factory = Composer.Instance.Single<IBrokerageFactory>(factory => factory.BrokerageType.MatchesTypeName(liveJob.Brokerage));
                }
                catch (Exception err)
                {
                    Log.Error("BrokerageSetupHandler.Setup(): Error resolving brokerage factory for " + liveJob.Brokerage + ". " + err.Message);
                    AddInitializationError("Unable to locate factory for brokerage: " + liveJob.Brokerage);
                }

                // let the world know what we're doing since logging in can take a minute
                resultHandler.SendStatusUpdate(job.AlgorithmId, AlgorithmStatus.LoggingIn, "Logging into brokerage...");

//.........这里部分代码省略.........
开发者ID:icecube11,项目名称:Lean,代码行数:101,代码来源:BrokerageSetupHandler.cs

示例13: GetRealTimeHandler

        /// <summary>
        /// Select the realtime event handler set in the job.
        /// </summary>
        private static IRealTimeHandler GetRealTimeHandler(IAlgorithm algorithm, IBrokerage brokerage, IDataFeed feed, IResultHandler results, AlgorithmNodePacket job)
        {
            var rth = default(IRealTimeHandler);
            switch (job.RealTimeEndpoint)
            {
                //Don't fire based on system time but virtualized backtesting time.
                case RealTimeEndpoint.Backtesting:
                    Log.Trace("Engine.GetRealTimeHandler(): Selected Backtesting RealTimeEvent Handler");
                    rth = new BacktestingRealTimeHandler(algorithm, job);
                    break;

                // Fire events based on real system clock time.
                case RealTimeEndpoint.LiveTrading:
                    Log.Trace("Engine.GetRealTimeHandler(): Selected LiveTrading RealTimeEvent Handler");
                    rth = new LiveTradingRealTimeHandler(algorithm, feed, results);
                    break;
            }
            return rth;
        }
开发者ID:sopnic,项目名称:Lean,代码行数:22,代码来源:Engine.cs

示例14: GetTransactionHandler

        /// <summary>
        /// Get an instance of the transaction handler set by the task.
        /// </summary>
        /// <param name="algorithm">Algorithm instance</param>
        /// <param name="job">Algorithm job packet</param>
        /// <param name="brokerage">Brokerage instance to avoid access token duplication</param>
        /// <param name="results">Results array for sending order events.</param>
        /// <returns>Class matching ITransactionHandler interface</returns>
        private static ITransactionHandler GetTransactionHandler(IAlgorithm algorithm, IBrokerage brokerage, IResultHandler results, AlgorithmNodePacket job)
        {
            ITransactionHandler th;
            switch (job.TransactionEndpoint)
            {
                case TransactionHandlerEndpoint.Brokerage:
                    th = new BrokerageTransactionHandler(algorithm, brokerage);
                    Log.Trace("Engine.GetTransactionHandler(): Selected Brokerage Transaction Models.");
                    break;

                //Operation from local files:
                default:
                    th = new BacktestingTransactionHandler(algorithm, brokerage as BacktestingBrokerage);
                    Log.Trace("Engine.GetTransactionHandler(): Selected Backtesting Transaction Models.");
                    break;
            }
            return th;
        }
开发者ID:sopnic,项目名称:Lean,代码行数:26,代码来源:Engine.cs

示例15: Setup

        /// <summary>
        /// Setup the algorithm cash, dates and data subscriptions as desired.
        /// </summary>
        /// <param name="algorithm">Algorithm instance</param>
        /// <param name="brokerage">Brokerage instance</param>
        /// <param name="baseJob">Algorithm job</param>
        /// <param name="resultHandler">The configured result handler</param>
        /// <param name="transactionHandler">The configurated transaction handler</param>
        /// <returns>Boolean true on successfully initializing the algorithm</returns>
        public bool Setup(IAlgorithm algorithm, out IBrokerage brokerage, AlgorithmNodePacket baseJob, IResultHandler resultHandler, ITransactionHandler transactionHandler)
        {
            var job = baseJob as BacktestNodePacket;
            if (job == null)
            {
                throw new ArgumentException("Expected BacktestNodePacket but received " + baseJob.GetType().Name);
            }

            Log.Trace(string.Format("BacktestingSetupHandler.Setup(): Setting up job: Plan: {0}, UID: {1}, PID: {2}, Version: {3}, Source: {4}", job.UserPlan, job.UserId, job.ProjectId, job.Version, job.RequestSource));

            brokerage = null;

            if (algorithm == null)
            {
                Errors.Add("Could not create instance of algorithm");
                return false;
            }

            //Make sure the algorithm start date ok.
            if (job.PeriodStart == default(DateTime))
            {
                Errors.Add("Algorithm start date was never set");
                return false;
            }

            //Execute the initialize code:
            var isolator = new Isolator();
            var initializeComplete = isolator.ExecuteWithTimeLimit(TimeSpan.FromSeconds(10), () =>
            {
                try
                {
                    //Algorithm is backtesting, not live:
                    algorithm.SetLiveMode(false);
                    //Set the backtest level asset ram allocation limits
                    algorithm.SetAssetLimits(500, 100, 30);
                    //Set the algorithm time before we even initialize:
                    algorithm.SetDateTime(job.PeriodStart);
                    //Initialise the algorithm, get the required data:
                    algorithm.Initialize();
                    //Add currency data feeds that weren't explicity added in Initialize
                    algorithm.Portfolio.CashBook.EnsureCurrencyDataFeeds(algorithm.Securities, algorithm.SubscriptionManager);
                }
                catch (Exception err)
                {
                    Errors.Add("Failed to initialize algorithm: Initialize(): " + err.Message);
                }
            });

            //Before continuing, detect if this is ready:
            if (!initializeComplete) return false;

            // this needs to be done after algorithm initialization
            brokerage = new BacktestingBrokerage(algorithm);

            SetupHandler.UpdateTransactionModels(algorithm, algorithm.BrokerageModel);
            algorithm.Transactions.SetOrderProcessor(transactionHandler);

            //Calculate the max runtime for the strategy
            _maxRuntime = GetMaximumRuntime(job.PeriodStart, job.PeriodFinish, algorithm.SubscriptionManager.Count);

            //Get starting capital:
            _startingCaptial = algorithm.Portfolio.Cash;

            //Max Orders: 10k per backtest:
            if (job.UserPlan == UserPlan.Free)
            {
                _maxOrders = 10000;
            }
            else
            {
                _maxOrders = int.MaxValue;
                _maxRuntime += _maxRuntime;
            }

            //Set back to the algorithm,
            algorithm.SetMaximumOrders(_maxOrders);

            //Starting date of the algorithm:
            _startingDate = job.PeriodStart;

            //Put into log for debugging:
            Log.Trace("SetUp Backtesting: User: " + job.UserId + " ProjectId: " + job.ProjectId + " AlgoId: " + job.AlgorithmId);
            Log.Trace("Dates: Start: " + job.PeriodStart.ToShortDateString() + " End: " + job.PeriodFinish.ToShortDateString() + " Cash: " + _startingCaptial.ToString("C"));

            if (Errors.Count > 0)
            {
                initializeComplete = false;
            }
            return initializeComplete;
        }
开发者ID:ssulliman,项目名称:Lean,代码行数:99,代码来源:BacktestingSetupHandler.cs


注:本文中的IBrokerage类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。