Esempio n. 1
0
        /// <summary>
        /// Add the signal to the list of the bar with barNo
        /// </summary>
        /// <param name="barNo"></param>
        /// <param name="signal"></param>
        public void AddTradeSignal(int barNo, SortedDictionary <int, List <TradeSignal> > listSignals, TradeSignal signal)
        {
            List <TradeSignal> list_signal;

            if (!listSignals.TryGetValue(barNo, out list_signal))
            {
                list_signal = new List <TradeSignal>();
            }
//			else
//				listSignals.Remove(barNo);

            list_signal.Add(signal);
            //listSignals.Add(barNo, list_signal);
            listSignals[barNo] = list_signal;
            IndicatorProxy.PrintLog(true, IsLiveTrading(),
                                    String.Format("{0}: AddTradeSignal list_signal.Count={1}, listSignals.Count={2}", CurrentBar, list_signal.Count, listSignals.Count));
            if (listSignals.Count < 5)
            {
                foreach (KeyValuePair <int, List <TradeSignal> > m in listSignals)
                {
                    List <TradeSignal> mm = m.Value as List <TradeSignal>;
                    foreach (TradeSignal ts in mm)
                    {
                        IndicatorProxy.PrintLog(true, IsLiveTrading(),
                                                String.Format("{0}: AddTradeSignal SortedDictionary key={1}, SignalType={2}", CurrentBar, m.Key, ts.SignalType.ToString()));
                    }
                }
            }
        }
        /// <summary>
        /// OnOrderUpdate->OnExecutionUpdate->OnPositionUpdate
        /// OnPositionUpdate: check new trade, change position for curTrade, no order update;
        /// OnExecutionUpdate: check filled order, update the new entry order and liquidate order;
        /// OnOrderUpdate: deal with working order, rejected/cancelled orders;
        /// </summary>
        /// <param name="order"></param>
        /// <param name="limitPrice"></param>
        /// <param name="stopPrice"></param>
        /// <param name="quantity"></param>
        /// <param name="filled"></param>
        /// <param name="averageFillPrice"></param>
        /// <param name="orderState"></param>
        /// <param name="time"></param>
        /// <param name="error"></param>
        /// <param name="comment"></param>
        protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice,
                                              int quantity, int filled, double averageFillPrice,
                                              Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
        {
            //if(BarsInProgress !=0) return;
            IndicatorProxy.Log2Disk = true;

            if (PrintOut > 1 && !IsInStrategyAnalyzer)
            {
                IndicatorProxy.PrintLog(true, IsLiveTrading(),
                                        CurrentBars[BarsInProgress] + "[" + BarsInProgress + "]:OnOrderUpdate IsUnmanaged=" + IsUnmanaged);
            }

            //The logic is implemented in the method below
            CurrentTrade.OnCurOrderUpdate(order, limitPrice, stopPrice, quantity, filled, averageFillPrice,
                                          orderState, time, error, comment);
            return;

            //The order execution is implemented in the method below
            if (IsUnmanaged)
            {
                OnOrderUpdateUM(order, limitPrice, stopPrice, quantity, filled,
                                averageFillPrice, orderState, time, error, comment);
            }
            else
            {
                OnOrderUpdateMG(order, limitPrice, stopPrice, quantity, filled,
                                averageFillPrice, orderState, time, error, comment);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Get the signal list for the bar by signal type
        /// </summary>
        /// <param name="barNo"></param>
        /// <param name="signal_type"></param>
        /// <returns></returns>
        public List <TradeSignal> GetTradeSignalByType(int barNo, SortedDictionary <int, List <TradeSignal> > listSignals, TradeSignalType signal_type)
        {
            List <TradeSignal> list_signal = GetTradeSignals(barNo, listSignals);

            IndicatorProxy.PrintLog(true, IsLiveTrading(),
                                    String.Format("{0}: GetTradeSignalByType signal_type={1}, list_signal={2}, listSignals.Count={3}",
                                                  CurrentBar, signal_type, list_signal, listSignals.Count));
            if (list_signal != null)
            {
                List <TradeSignal> list_sigByType = new List <TradeSignal>();
                foreach (TradeSignal sig in list_signal)
                {
                    //if(list_signal.Count >= 1)
                    if (signal_type == sig.SignalType)
                    {
                        IndicatorProxy.PrintLog(true, IsLiveTrading(),
                                                String.Format("{0}: GetTradeSignalByType== signal_type={1}, sig.SignalType={2}, list_signal.Count={3}",
                                                              CurrentBar, signal_type, sig.SignalType, list_signal.Count));
                        list_sigByType.Add(sig);
                    }
                }
                if (list_sigByType.Count > 0)
                {
                    return(list_sigByType);
                }
            }

            return(null);
        }
Esempio n. 4
0
        protected override void OnBarUpdate()
        {
            if (CurrentBar < BarsRequiredToTrade)
            {
                return;
            }
            giPctSpd.Update();
            IndicatorProxy.Update();
            if (CheckPnLByBarsSinceEn())
            {
                OnExitPositions(null);
            }
//			if(BarsInProgress == BarsArray.Length-1)
//				OnTradeByPctSpd();
            // Note: Bars are added to the BarsArray and can be accessed via an index value
            // E.G. BarsArray[1] ---> Accesses the 1 minute Bars added above
//			if (adx1 == null)
//				adx1 = ADX(BarsArray[1], 14);

            // OnBarUpdate() will be called on incoming tick events on all Bars objects added to the strategy
            // We only want to process events on our primary Bars object (main instrument) (index = 0) which
            // is set when adding the strategy to a chart
            if (BarsInProgress != 0)
            {
                return;
            }
            if (CurrentBars[0] < 0 || CurrentBars[1] < 0)
            {
                return;
            }

            // Checks if the 14 period ADX on both instruments are trending (above a value of 30)
            if (adx[0] > 30 && adx1[0] > 30)
            {
                // If RSI crosses above a value of 30 then enter a long position via a limit order
                if (CrossAbove(rsi, 30, 1))
                {
                    // Draws a square 1 tick above the high of the bar identifying when a limit order is issued
                    Draw.Square(this, "My Square" + CurrentBar, false, 0, High[0] + TickSize, Brushes.DodgerBlue);

                    // Enter a long position via a limit order at the current ask price
                    //EnterLongLimit(GetCurrentAsk(), "RSI");
                    //EnterLong(1);
//					EnterLong(0, 1, "RSI");
//					EnterShort(1, 1, "RSI");
//					EnterShort(2, 1, "RSI");
                }
            }

            // Any open long position will exit if RSI crosses below a value of 75
            // This is in addition to the trail stop set in the OnStateChange() method under State.Configure
            if (CrossBelow(rsi, 75, 1))
            {
                //ExitLong();
//				ExitLong(0, 1, "ExitRSI", "RSI");
//				ExitShort(1, 1, "ExitRSI", "RSI");
//				ExitShort(2, 1, "ExitRSI", "RSI");
            }
        }
Esempio n. 5
0
        /// <summary>
        ///
        /// </summary>
        public virtual void TakeTradeAction()
        {
            //CurrentTrade.TradeAction = GetTradeAction(CurrentBar);//??
            try {
                TradeAction ta = CurrentTrade.TradeAction;
                if (ta == null || ta.ActionStatus == TradeActionStatus.Executed)
                {
                    IndicatorProxy.PrintLog(true, IsLiveTrading(),
                                            String.Format("{0}:TakeTradeAction called, CurrentTrade.TradeAction=null or Executed=={1}",
                                                          CurrentBar, ta.ActionStatus.ToString()));
                    return;
                }
                String sigName = "UnKnown";
                if (ta.EntrySignal != null)
                {
                    sigName = ta.EntrySignal.SignalName;
                }
                if (ta.StopLossSignal != null)
                {
                    sigName = ta.StopLossSignal.SignalName;
                }
                if (ta.ProfitTargetSignal != null)
                {
                    sigName = ta.ProfitTargetSignal.SignalName;
                }
                if (ta.ScaleOutSignal != null)
                {
                    sigName = ta.ScaleOutSignal.SignalName;
                }

                IndicatorProxy.PrintLog(true, IsLiveTrading(), CurrentBar + ":TakeTradeAction"
                                        + ";SignalName=" + sigName
                                        + ";ActionName=" + ta.ActionName
                                        + ";ActionType=" + ta.ActionType.ToString()
                                        + ";CurrentTrade.TDID=" + CurrentTrade.TradeID
                                        + ";OcoID=" + CurrentTrade.OcoID
                                        + ";HasPosition=" + HasPosition());

                ta.ActionStatus = TradeActionStatus.Executed;
                switch (ta.ActionType)
                {
                case TradeActionType.EntrySimple:
                case TradeActionType.Bracket:
                    PutEntryTrade();
                    break;

                case TradeActionType.ExitOCO:
                    PutExitTrade();
                    break;

                case TradeActionType.ExitSimple:
                    PutLiquidateTrade();
                    break;
                }
            } catch (Exception ex) {
                IndicatorProxy.PrintLog(true, IsLiveTrading(),
                                        CurrentBar + ":Exception TakeTradeAction--" + ex.StackTrace);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Get the signal list for the bar
        /// </summary>
        /// <param name="barNo"></param>
        /// <returns></returns>
        public List <TradeSignal> GetTradeSignals(int barNo, SortedDictionary <int, List <TradeSignal> > listSignals)
        {
            List <TradeSignal> list_signal;

            listSignals.TryGetValue(barNo, out list_signal);
            //	return null;
            //else
            IndicatorProxy.PrintLog(true, IsLiveTrading(),
                                    String.Format("{0}: GetTradeSignals list_signal.Count={1}, listSignals.Count={2}", CurrentBar, list_signal, listSignals.Count));
            return(list_signal);
        }
Esempio n. 7
0
        protected double GetTimeSinceEntry()
        {
            int    bse         = BarsSinceEntryExecution();
            double timeSinceEn = -1;

            if (bse > 0)
            {
                timeSinceEn = IndicatorProxy.GetMinutesDiff(Time[0], Time[bse]);
            }
            return(timeSinceEn);
        }
Esempio n. 8
0
        /// <summary>
        /// Check if now is the time to liquidate
        /// </summary>
        /// <param name="timeH">time hour</param>
        /// <param name="timeM">time min</param>
        /// <returns></returns>
        public bool IsLiquidateTime(int timeH, int timeM)
        {
            int  time_now     = IndicatorProxy.GetTimeByHM(Time[0].Hour, Time[0].Minute, true);
            int  time_lastBar = IndicatorProxy.GetTimeByHM(Time[1].Hour, Time[1].Minute, true);
            int  time_liq     = IndicatorProxy.GetTimeByHM(timeH, timeM, true);
            bool isTime       = false;

            if (time_now == time_liq || (time_liq > time_lastBar && time_liq <= time_now))
            {
                isTime = true;
            }
            return(isTime);
        }
Esempio n. 9
0
        // Define what actions to take when the event is raised.

        void OnTradeByPairSpdRs(object sender, IndicatorEventArgs e)
        {
            IndicatorSignal isig = e.IndSignal;

            //Print(String.Format("{0}:OnTradeByPairSpdRs triggerred {1} Bip{2}: Spread={3}, Middle={4}",
            //CurrentBars[BarsInProgress], isig.SignalName, BarsInProgress, giSpdRs.Spread[0], giSpdRs.Middle[0]));
            if (e.IndSignal.SignalName != null && HasPairPosition())
            {
                OnExitPositions(e);
            }
            else if (e.IndSignal.SignalName != null && IsTradingTime(IndicatorProxy.GetTimeByHM(TG_OpenStartH, TG_OpenStartM, true)))
            {
                OnEntryPositions(e);
            }
        }
Esempio n. 10
0
        public bool HasPairPosition(int startIndex)
        {
            if (PrintOut > 1 && !IsInStrategyAnalyzer)
            {
                IndicatorProxy.TraceMessage(this.Name, 0);
            }
            bool pos = false;

            if (GetMarketPosition(startIndex) != MarketPosition.Flat &&
                GetMarketPosition(startIndex + 1) != MarketPosition.Flat)
            {
                pos = true;
            }
            return(pos);
        }
Esempio n. 11
0
        public override bool IsTradingTime(int session_start)
        {
            //Bars.Session.GetNextBeginEnd(DateTime time, out DateTime sessionBegin, out DateTime sessionEnd)
            int  time_start = IndicatorProxy.GetTimeByHM(TG_TradeStartH, TG_TradeStartM, true);
            int  time_end   = IndicatorProxy.GetTimeByHM(TG_TradeEndH, TG_TradeEndM, true);
            int  time_now   = ToTime(Time[0]);
            bool isTime     = (BarsPeriod.BarsPeriodType == BarsPeriodType.Day)? true : false;

            if (time_now >= session_start && time_now >= time_start && time_now <= time_end)
            {
                isTime = true;
            }
//			Print(String.Format("{0}: time_now={1}, session_start={2}, time_start={3}, time_end={4}, isTime={5}",
//			CurrentBar, time_now, session_start, time_start, time_end, isTime));
            return(isTime);
        }
Esempio n. 12
0
        // Define what actions to take when the event is raised.

        void OnTradeBySpdLadder(object sender, IndicatorEventArgs e)
        {
            IndicatorSignal isig = e.IndSignal;

            if (this.PrintOut > 1)
            {
                Print(String.Format("{0}:OnTradeBySpdLadder triggerred {1} Bip{2}: Spread={3}, HiAllTime={4}",
                                    CurrentBars[BarsInProgress], isig.SignalName, BarsInProgress, giSpdLadder.Spread[0], giSpdLadder.HiAllTime));
            }
            if (e.IndSignal.SignalName != null && HasPairPosition())
            {
                OnExitPositions(e);
            }
            else if (e.IndSignal.SignalName != null && IsTradingTime(IndicatorProxy.GetTimeByHM(TG_OpenStartH, TG_OpenStartM, true)))
            {
                OnEntryPositions(e);
            }
        }
        /// <summary>
        /// Only updated on live/sim trading, not triggered at back-testing;
        /// The evernt posted tick by tick at sim/living trading with poistion hold;
        /// </summary>
        /// <param name="account"></param>
        /// <param name="accountItem"></param>
        /// <param name="value"></param>
        protected override void OnAccountItemUpdate(Cbi.Account account, Cbi.AccountItem accountItem, double value)
        {
            if (account == null || accountItem == null || IndicatorProxy == null)
            {
                return;
            }

            if (accountItem == AccountItem.UnrealizedProfitLoss && PrintOut > 2 && !IsInStrategyAnalyzer)
            {
                IndicatorProxy.PrintLog(true, IsLiveTrading(),                 //":OnAccountItemUpdate"
                                        CurrentBar + ":OnAccountItemUpdate"
                                        + ";Name=" + account.DisplayName
                                        + ";Item=" + accountItem.ToString()
                                        + ";value=" + value
                                        + ";DailyLossLmt=" + account.DailyLossLimit
                                        + ";Status=" + account.AccountStatus.ToString()
                                        );
            }
        }
Esempio n. 14
0
        // Define what actions to take when the event is raised.

        void OnTradeByPairPctSpd(object sender, IndicatorEventArgs e)
        {
            IndicatorSignal isig = e.IndSignal;

            Print(String.Format("{0}:OnTradeByPairPctSpd triggerred {1} Bip{2}: PlotPctSpd={3}, PctChgSpdThresholdEn={4}",
                                CurrentBars[BarsInProgress], isig.SignalName, BarsInProgress, giPairPctSpd.PlotPctSpd[0], giPairPctSpd.PctChgSpdThresholdEn));
            if (IsTradingTime(IndicatorProxy.GetTimeByHM(TG_OpenStartH, TG_OpenStartM, true)) && giPairPctSpd.PlotPctSpd[0] <= PctChgSpdThresholdEn)
            {
                OnEntryPositions(e);
            }
            else
            {
                OnExitPositions(e);
            }

            /*
             * int q_max = GetTradeQuantity(giPctSpd.PctChgMaxBip, this.MM_ProfitFactorMax);
             * int q_min = GetTradeQuantity(giPctSpd.PctChgMinBip, this.MM_ProfitFactorMin);
             *
             * //exit at 9:40 am ct
             * if(isig.SignalName == giPctSpd.SignalName_ExitForOpen) {
             *      Print(String.Format("{0}:OnTradeByPctSpd Ex Bip={1}: MaxBip={2}, PosMax={3},  MinBip={4}, PosMin={5}",
             *      CurrentBars[BarsInProgress], BarsInProgress, giPctSpd.PctChgMaxBip, Positions[giPctSpd.PctChgMaxBip], giPctSpd.PctChgMinBip, Positions[giPctSpd.PctChgMinBip]));
             *      OnExitPositions(e);
             * } else { //entry at 9:02 am ct
             *      Print(String.Format("{0}:OnTradeByPctSpd En Bip={1}: PctSpd={2}, MaxBip={3}, MinBip={4}",
             *      CurrentBar, BarsInProgress, giPctSpd.PlotPctSpd[0], giPctSpd.PctChgMaxBip, giPctSpd.PctChgMinBip));
             *      if(isig.TrendDir.TrendDir == TrendDirection.Up) {
             *              IndicatorProxy.PrintLog(true, IsLiveTrading(),String.Format("{0}:{1} Ln Bip={2}: PctSpd={3}, MaxBipQuant={4}, MinBipQuant={5}",
             *              CurrentBars[BarsInProgress], e.Message, BarsInProgress, giPctSpd.PlotPctSpd[0],
             *              q_max, q_min));
             *              EnterLong(giPctSpd.PctChgMaxBip, q_max, "GIPctSpd");
             *              EnterShort(giPctSpd.PctChgMinBip, q_min, "GIPctSpd");
             *      }
             *      else if(isig.TrendDir.TrendDir == TrendDirection.Down) {
             *              IndicatorProxy.PrintLog(true, IsLiveTrading(),String.Format("{0}:{1} St Bip={2}: PctSpd={3}, MaxBipQuant={4}, MinBipQuant={5}",
             *              CurrentBars[BarsInProgress], e.Message, BarsInProgress, giPctSpd.PlotPctSpd[0],
             *              q_max, q_min));
             *              EnterShort(giPctSpd.PctChgMaxBip, q_max, "GIPctSpd");
             *              EnterLong(giPctSpd.PctChgMinBip, q_min, "GIPctSpd");
             *      }
             * } */
        }
Esempio n. 15
0
        public int HasPosition()
        {
            if (PrintOut > 1 && !IsInStrategyAnalyzer)
            {
                IndicatorProxy.TraceMessage(this.Name, 0);
            }
            int pos = 0;

            if (IsLiveTrading())
            {
                //if(PositionAccount != null)
                pos = PositionAccount.Quantity;
            }
            else             //if(Position != null)
            {
                pos = Position.Quantity;
            }
            return(pos);
        }
        protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition,
                                                  string orderId, DateTime time)
        {
            if (BarsInProgress != 0)
            {
                return;
            }
            IndicatorProxy.Log2Disk = true;
            if (PrintOut > 1 && !IsInStrategyAnalyzer)
            {
                IndicatorProxy.PrintLog(true, IsLiveTrading(),
                                        CurrentBar + ":OnExecutionUpdate"
                                        + ";IsUnmanaged=" + IsUnmanaged
                                        + ";IsLiveTrading=" + IsLiveTrading()
                                        + ";IsInitialEntry=" + execution.IsInitialEntry
                                        + ";IsEntry=" + execution.IsEntry
                                        + ";IsExit=" + execution.IsExit
                                        + ";IsLastExit=" + execution.IsLastExit
                                        + ";GetMarketPosition=" + GetMarketPosition()
                                        + ";marketPosition=" + marketPosition
                                        + ";quantity=" + quantity
                                        + ";HasPosition=" + HasPosition()
                                        + ";GetAvgPrice=" + GetAvgPrice()
                                        + ";price=" + price);
            }

            CurrentTrade.OnCurExecutionUpdate(execution, executionId, price, quantity, marketPosition, orderId, time);
            return;

            if (IsUnmanaged)
            {
                OnExecutionUpdateUM(execution, executionId, price, quantity, marketPosition, orderId, time);
            }
            else
            {
                OnExecutionUpdateMG(execution, executionId, price, quantity, marketPosition, orderId, time);
            }
        }
Esempio n. 17
0
        // Define what actions to take when the event is raised.
        void OnTradeByPctSpd(object sender, IndicatorEventArgs e)
        {
            IndicatorSignal isig = e.IndSignal;

            Print(String.Format("{0}:OnTradeByPctSpd triggerred {1} Bip{2}: PctSpd={3}, MaxBip={4}, MinBip={5}",
                                CurrentBars[BarsInProgress], isig.SignalName, BarsInProgress, giPctSpd.PlotPctSpd[0], giPctSpd.PctChgMaxBip, giPctSpd.PctChgMinBip));
            int q_max = GetTradeQuantity(giPctSpd.PctChgMaxBip, this.MM_ProfitFactorMax);
            int q_min = GetTradeQuantity(giPctSpd.PctChgMinBip, this.MM_ProfitFactorMin);

            //exit at 9:40 am ct
            if (isig.SignalName == giPctSpd.SignalName_ExitForOpen)
            {
                Print(String.Format("{0}:OnTradeByPctSpd Ex Bip={1}: MaxBip={2}, PosMax={3},  MinBip={4}, PosMin={5}",
                                    CurrentBars[BarsInProgress], BarsInProgress, giPctSpd.PctChgMaxBip, Positions[giPctSpd.PctChgMaxBip], giPctSpd.PctChgMinBip, Positions[giPctSpd.PctChgMinBip]));
                OnExitPositions(e);
            }
            else                 //entry at 9:02 am ct
            {
                Print(String.Format("{0}:OnTradeByPctSpd En Bip={1}: PctSpd={2}, MaxBip={3}, MinBip={4}",
                                    CurrentBar, BarsInProgress, giPctSpd.PlotPctSpd[0], giPctSpd.PctChgMaxBip, giPctSpd.PctChgMinBip));
                if (isig.TrendDir.TrendDir == TrendDirection.Up)
                {
                    IndicatorProxy.PrintLog(true, IsLiveTrading(), String.Format("{0}:{1} Ln Bip={2}: PctSpd={3}, MaxBipQuant={4}, MinBipQuant={5}",
                                                                                 CurrentBars[BarsInProgress], e.Message, BarsInProgress, giPctSpd.PlotPctSpd[0],
                                                                                 q_max, q_min));
                    EnterLong(giPctSpd.PctChgMaxBip, q_max, "GIPctSpd");
                    EnterShort(giPctSpd.PctChgMinBip, q_min, "GIPctSpd");
                }
                else if (isig.TrendDir.TrendDir == TrendDirection.Down)
                {
                    IndicatorProxy.PrintLog(true, IsLiveTrading(), String.Format("{0}:{1} St Bip={2}: PctSpd={3}, MaxBipQuant={4}, MinBipQuant={5}",
                                                                                 CurrentBars[BarsInProgress], e.Message, BarsInProgress, giPctSpd.PlotPctSpd[0],
                                                                                 q_max, q_min));
                    EnterShort(giPctSpd.PctChgMaxBip, q_max, "GIPctSpd");
                    EnterLong(giPctSpd.PctChgMinBip, q_min, "GIPctSpd");
                }
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Check if now is the time allowed to put trade
        /// </summary>
        /// <param name="time_start">start time</param>
        /// <param name="time_end">end time</param>
        /// <param name="session_start">the overnight session start time: 170000 for ES</param>
        /// <returns></returns>
        public virtual bool IsTradingTime(int session_start)
        {
            //Bars.Session.GetNextBeginEnd(DateTime time, out DateTime sessionBegin, out DateTime sessionEnd)
            int  time_start = IndicatorProxy.GetTimeByHM(TG_TradeStartH, TG_TradeStartM, true);
            int  time_end   = IndicatorProxy.GetTimeByHM(TG_TradeEndH, TG_TradeEndM, true);
            int  time_now   = ToTime(Time[0]);
            bool isTime     = false;

            if (time_start >= session_start)
            {
                if (time_now >= time_start || time_now <= time_end)
                {
                    isTime = true;
                }
            }
            else if (time_now >= time_start && time_now <= time_end)
            {
                isTime = true;
            }
            Print(String.Format("{0}: time_now={1}, session_start={2}, time_start={3}, time_end={4}, isTime={5}",
                                CurrentBar, time_now, session_start, time_start, time_end, isTime));
            return(isTime);
        }
Esempio n. 19
0
        protected override void OnPositionUpdate(Cbi.Position position, double averagePrice,
                                                 int quantity, Cbi.MarketPosition marketPosition)
        {
            IndicatorProxy.Log2Disk = true;
            int bsx = BarsSinceExitExecution(0, "", 0);
            int bse = BarsSinceEntryExecution(0, "", 0);

            if (PrintOut > 1 && !IsInStrategyAnalyzer)
            {
                IndicatorProxy.PrintLog(true, IsLiveTrading(),
                                        CurrentBar + ":OnPositionUpdate, CurrentTrade not updated -- "
                                        + ";BarsSinceExit, BarsSinceEntry="
                                        + bsx + "," + bse
                                        + ";IsUnmanaged=" + IsUnmanaged
                                        + ";IsLiveTrading=" + IsLiveTrading()
                                        + ";GetMarketPosition=" + GetMarketPosition()
                                        + ";marketPosition=" + marketPosition
                                        + ";HasPosition=" + HasPosition()
                                        + ";CurrentTrade.PosQuantity=" + CurrentTrade.PosQuantity
                                        + ";CurrentTrade.MktPosition=" + CurrentTrade.MktPosition
                                        + ";quantity=" + quantity
                                        + ";GetAvgPrice=" + GetAvgPrice()
                                        + ";averagePrice=" + averagePrice);
            }
            //Print(position.ToString() + "--MarketPosition=" + position.MarketPosition);
            CurrentTrade.OnCurPositionUpdate(position, averagePrice, quantity, marketPosition);
            if (CurrentTrade.MktPosition != null && CurrentTrade.PosAvgPrice != null &&
                CurrentTrade.PosQuantity != null && CurrentTrade.PosUnrealizedPnL != null)
            {
                if (PrintOut > 1 && !IsInStrategyAnalyzer)
                {
                    IndicatorProxy.PrintLog(true, IsLiveTrading(),
                                            String.Format("{0}: OnPositionUpdate, CurrentTrade updated -- CurrentTrade.PosAvgPrice: {1}, CurrentTrade.PosQuantit={2}, CurrentTrade.MktPosition={3}, PnL={4}",
                                                          CurrentBar, CurrentTrade.PosAvgPrice, CurrentTrade.PosQuantity, CurrentTrade.MktPosition, CurrentTrade.PosUnrealizedPnL));
                }
            }
        }
        /// <summary>
        /// The first event handler for each bar;
        /// Other handlers like OnOrderUpdate, OnExecutionUpdate, OnPositionUpdate,
        /// are used to setup status for CurrentTrade, the TradeAction will be taken
        /// on the next bar(CurrentBar+1) at OnBarUpdate;
        /// The command and performance triggerred TradeAction can be taken at the
        /// same bar at PutTrade();
        /// </summary>
        protected override void OnBarUpdate()
        {
            if (PrintOut > 1 && !IsInStrategyAnalyzer)
            {
                IndicatorProxy.PrintLog(true, IsLiveTrading(),
                                        String.Format("{0}:===========OnBarUpdate======HasPosition={1}, IsLiveTrading={2}",
                                                      CurrentBar, HasPosition(), IsLiveTrading()));
                IndicatorProxy.TraceMessage(this.Name, PrintOut);
            }
            //Print(CurrentBar.ToString() + " -- GSZTraderBase - Add your custom strategy logic here.");
            if (CurrentBar <= BarsRequiredToTrade)
            {
                return;
            }
            int bsx = BarsSinceExitExecution(0, "", 0);
            int bse = BarsSinceEntryExecution(0, "", 0);

            SetPrintOut(-1);
            //Print(CurrentBar + ":" + this.Name + " OnBarUpdate, BarsSinceExit, BarsSinceEntry=" + bsx + "," + bse);
            if (PrintOut > 1 && !IsInStrategyAnalyzer)
            {
                IndicatorProxy.TraceMessage(this.Name, PrintOut);
            }
            IndicatorProxy.Update();
            if (PrintOut > 1 && !IsInStrategyAnalyzer)
            {
                IndicatorProxy.TraceMessage(this.Name, PrintOut);
            }
            CheckCmd();             //Command trigger

            switch (AlgoMode)
            {
            case AlgoModeType.Liquidate:                     //liquidate
                if (PrintOut > 1 && !IsInStrategyAnalyzer)
                {
                    IndicatorProxy.TraceMessage(this.Name, PrintOut);
                }
                CloseAllPositions();
                break;

            case AlgoModeType.CancelOrders:                     //cancel order
                if (PrintOut > 1 && !IsInStrategyAnalyzer)
                {
                    IndicatorProxy.TraceMessage(this.Name, PrintOut);
                }
                CancelAllOrders();
                break;

            case AlgoModeType.StopTrading:                     // -2=stop trading(no entry/exit, liquidate positions and cancel all entry/exit orders);
                CancelAllOrders();
                CloseAllPositions();
                if (PrintOut > 1 && !IsInStrategyAnalyzer)
                {
                    IndicatorProxy.TraceMessage(this.Name, PrintOut);
                    IndicatorProxy.PrintLog(true, IsLiveTrading(), CurrentBar + "- Stop trading cmd:" + IndicatorProxy.Get24HDateTime(Time[0]));
                }
                break;

            case AlgoModeType.ExitOnly:                     // -1=stop trading(no entry/exit, cancel entry orders and keep the exit order as it is if there has position);
                CancelEntryOrders();
                break;

            case AlgoModeType.Trading:                     //trading
                //SetTradeAction(); called from CheckExitTrade() or CheckNewEntryTrade();
                //CheckIndicatorSignals(); called from SetTradeAction(); save trade signals into the trade action;
                //PutTrade(); first GetTradeAction() and then put exit or entry trade;
                if (PrintOut > 1 && !IsInStrategyAnalyzer)
                {
                    IndicatorProxy.TraceMessage(this.Name, PrintOut);
                }
                //CheckPerformance(); //Performance/Rule trigger
                //SetTradeAction();
                if (HasPosition() != 0)
                {
                    CheckPerformance();
                }
                //Produce trade signals from indicator indicator signals
                CheckIndicatorSignals();
                //Set trade action replaced by the event hanlder from indicator signals
                SetTradeAction();
                //PutTrade();
                TakeTradeAction();
                break;

            case AlgoModeType.SemiAlgo:                         // 2=semi-algo(manual entry, algo exit);
                if (HasPosition() != 0)
                {
                    CheckPerformance();                             //Performance/Rule trigger
                    //ChangeSLPT(); //re-implement to fit TradeAction process
                    //Produce trade signals from indicator indicator signals
                    CheckIndicatorSignals();
                    SetTradeAction();
                    //PutTrade();
                    TakeTradeAction();
                }
                break;
            }

            if (PrintOut > 1 && !IsInStrategyAnalyzer)
            {
                IndicatorProxy.TraceMessage(this.Name, PrintOut);
            }
        }