Overall Statistics
Total Trades
8498
Average Win
0.03%
Average Loss
-0.04%
Compounding Annual Return
40.000%
Drawdown
12.100%
Expectancy
0.195
Net Profit
40.733%
Sharpe Ratio
1.832
Probabilistic Sharpe Ratio
82.491%
Loss Rate
30%
Win Rate
70%
Profit-Loss Ratio
0.70
Alpha
0.25
Beta
-0.15
Annual Standard Deviation
0.132
Annual Variance
0.017
Information Ratio
0.757
Tracking Error
0.25
Treynor Ratio
-1.615
Total Fees
$0.00
### <summary>
### In this example, implementing simple algo
### </summary>

import clr
clr.AddReference("System")
clr.AddReference("QuantConnect.Algorithm")
clr.AddReference("QuantConnect.Indicators")
clr.AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
#from QuantConnect.Algorithm import *
#from QuantConnect.Indicators import *
import numpy as np
import json 

class CurrPairs:
    def __init__(self, cpName0, FxData0, PendingBuy0 = 0, PendingSell0 = 0, DefaultUnit0 = 1000, 
            OrderDiffPip0 = 10, LastTradeId0 = 0, LastTradePrice0 = 0.0, LastTradeUnit0 = 0, 
            LastBuyTradeId0 = 0, LastOpenBuyOrderId0 = 0, LastCloseBuyOrderId0 = 0, LastSellTradeId0 = 0, 
            LastOpenSellOrderId0 = 0,LastCloseSellOrderId0 = 0,
            AvgBuyCount0 = 0.0, AvgBuyDist0 = 0.0, MaxBuyCount0 = 0, MaxBuyDist0 = 0.0, BuyCount0 = 0, 
            AvgSellCount0 = 0.0, AvgSellDist0 = 0.0, MaxSellCount0 = 0, MaxSellDist0 = 0.0, 
            SellCount0 = 0, ChngCount0 = 0, AvgChngDist0 = 0.0, MaxChngDist0 = 0.0, PlusOverride0 = 1.05, 
            MinusOverride0 = 1.05, TakeProfitCount0 = 20.0, HoldingUnit0 = 0, DefaultLong0 = True, 
            OnePip0 = 0.0001, MinProfitPip0 = 25, MaxHolding0 = 50000, MinHolding0 = 500 ):
        self.cpName = cpName0
        self.FxData = FxData0 
        self.PendingBuy = PendingBuy0 
        self.PendingSell = PendingSell0  
        self.DefaultUnit = DefaultUnit0 
        self.OrderDiffPip = OrderDiffPip0
        self.OrderDiff = OrderDiffPip0 * OnePip0
        self.LastTradeId = LastTradeId0  
        self.LastTradePrice = LastTradePrice0 
        self.LastTradeUnit = LastTradeUnit0  
        self.LastBuyTradeId = LastBuyTradeId0 
        self.LastOpenBuyOrderId = LastOpenBuyOrderId0 
        self.LastCloseBuyOrderId = LastCloseBuyOrderId0 
        self.LastSellTradeId = LastSellTradeId0 
        self.LastOpenSellOrderId = LastOpenSellOrderId0 
        self.LastCloseSellOrderId = LastCloseSellOrderId0 
        self.Price = 0.0
        self.PrevPrice = 0.0
        self.PriceMove = 0
        self.AvgBuyCount = AvgBuyCount0 
        self.AvgBuyDist = AvgBuyDist0
        self.MaxBuyCount = MaxBuyCount0
        self.MaxBuyDist = MaxBuyDist0
        self.BuyCount = BuyCount0
        self.AvgSellCount = AvgSellCount0
        self.AvgSellDist = AvgSellDist0
        self.MaxSellCount = MaxSellCount0
        self.MaxSellDist = MaxSellDist0
        self.SellCount = SellCount0
        self.ChngCount = ChngCount0
        self.AvgChngDist = AvgChngDist0
        self.MaxChngDist = MaxChngDist0
        self.PlusOverride = PlusOverride0  
        self.MinusOverride = MinusOverride0
        self.TakeProfitCount = TakeProfitCount0
        self.HoldingUnit = HoldingUnit0
        self.DefaultLong = DefaultLong0
        self.OnePip = OnePip0 
        self.MinProfitPip = MinProfitPip0  
        self.MinProfit = MinProfitPip0 * OnePip0
        self.MaxHolding = MaxHolding0 
        self.MinHolding = MinHolding0
        
class  GenericCounters:

    def __init__(self):
        self.CounterValues = {}
        
    def new (self, CounterName, StartValue = 0):
        self.CounterValues[CounterName] = StartValue
        return self.CounterValues[CounterName]
    
    def inc (self, CounterName, increment = 1):
        self.CounterValues[CounterName] += increment
        return self.CounterValues[CounterName]
    
    def dec (self, CounterName, decrement = 1):
        self.CounterValues[CounterName] -= decrement
        return self.CounterValues[CounterName]

### <meta name="tag" content="strategy example" />
class SR000100(QCAlgorithm):

#    def mylog (self, inObj = b''):
#        return json.JSONEncoder().encode(inObj)
#        self.Log( str(inObj, encoding='utf-8', errors='strict') )
#        self.Log( inObj.ToString())
#
#    def mylog (self, strObj = ""):
#        return json.JSONEncoder().encode(inObj)
#        self.Log( strObj) 
#        
    def mylog (self, strObj = "", *argv ):
#        return
#        self.Log( strObj + ">")
        LineOut = strObj + ">"
        cntr = 0
        for arg in argv:
#            self.Log( str(arg, encoding='utf-8', errors='strict') )
#            self.Log("{0}: {1!s}: {2!r}".format(arg, arg, arg))
            cntr += 1
            LineOut += "|{0}:{1} :".format(cntr , arg)
#            LineOut += "|{1} ".format(cntr , arg)
        LineOut += "<# "
        self.Log(LineOut) 
#        self.Log( strObj + "<:End::")

    def updateCounters(self, OrderEvent, OT, CallerID):

        NewTag = OT.Tag + CallerID + ":OiD-{0}:".format(OT.OrderId)
        self.mylog(CallerID+"FO Tag-update:", OT.OrderId, OT.Symbol, OT.Quantity, OT.Time, OT.Status, OT.Tag, NewTag)

        CP = self.fxPairs[OrderEvent.Symbol.Value]
        CP.HoldingUnit = CP.HoldingUnit + OrderEvent.FillQuantity
        CP.LastTradeId = OrderEvent.OrderId  
        CP.LastTradePrice = OrderEvent.FillPrice 
        CP.LastTradeUnit = OrderEvent.FillQuantity  
        if OrderEvent.FillQuantity > 0 :  # Buy Fill 
            CP.LastBuyTradeId = OrderEvent.OrderId  
        elif OrderEvent.FillQuantity < 0 : # Sell Fill
            CP.LastSellTradeId = OrderEvent.OrderId  
            
        self.mylog(CallerID+"updateCounters:", CP.cpName, CP.Price, CP.PendingBuy, CP.PendingSell,  
                CP.LastTradeId, CP.LastTradePrice, CP.LastTradeUnit, 
                CP.LastBuyTradeId, CP.LastOpenBuyOrderId, CP.LastCloseBuyOrderId, CP.LastSellTradeId, 
                CP.LastOpenSellOrderId, CP.LastCloseSellOrderId,
                CP.AvgBuyCount, CP.AvgBuyDist, CP.MaxBuyCount, CP.MaxBuyDist, CP.BuyCount, 
                CP.AvgSellCount, CP.AvgSellDist, CP.MaxSellCount, CP.MaxSellDist, 
                CP.SellCount, CP.ChngCount, CP.AvgChngDist, CP.MaxChngDist, CP.PlusOverride, 
                CP.MinusOverride, CP.TakeProfitCount, CP.HoldingUnit, self.Portfolio[OrderEvent.Symbol].Quantity  )


    def formatBuyPrice(self, Price, DiffPip, OnePip):
        return (Price - Price %(DiffPip * OnePip)) 

    def formatSellPrice(self, Price, DiffPip, OnePip):
        HalfDiff = DiffPip * OnePip / 2.0
        return (Price + ((-Price - HalfDiff) %(DiffPip * OnePip))) 

    def Initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
        # create Datasets to store current status for all symbols 
        # forex pairs
        self.OpenTag = "open"
        self.CloseTag = "close"
        
        self.FCC = GenericCounters()
        self.FCC.new("DP")   # DataPoint
        self.FCC.new("OE")  # OrderEvent
        self.FCC.new("OC")  # OrderCount
        self.FCC.new("OBO") # OpenBuyOrder
        self.FCC.new("CBO") # CloseBuyOrder
        self.FCC.new("OSO") # OpenSellOrder
        self.FCC.new("CSO") # CloseSellOrder
        
        self.DefaultOrderProperties.TimeInForce = TimeInForce.GoodTilCanceled
#        self.symbols = ["EURUSD", "EURGBP", "GBPUSD"]
#        self.ShortPairs = ["EURUSD", "EURGBP", "GBPUSD"]
        self.symbols = ["EURUSD"]
        self.ShortPairs = ["EURUSD"]
        PairsCount30 = len(self.symbols)

        self.SetStartDate(2010, 12, 3)    #Set Start Date
        self.SetEndDate(2019, 12, 6)      #Set End Date
        self.SetCash(PairsCount30 * 10000)    #Set Strategy Cash
        self.fxPairs = {}

        # Initialize status data set 
        for symbol in self.symbols:
            fxData = self.AddForex(symbol, Resolution.Hour, Market.Oanda, True, 50.0 )
#            CP = CurrPairs(symbol, fxData )
            self.fxPairs[symbol] = CurrPairs(symbol, fxData )
            if symbol in self.ShortPairs :
                self.fxPairs[symbol].DefaultLong = False

    def OnData(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
        DP = "DP:{0}:".format(self.FCC.inc("DP"))
        for key in data.Keys:
            CP = self.fxPairs[key.Value]
            CP.Price = self.Securities[key.Value].Price
            CP.PriceMove = (CP.Price - CP.PrevPrice) 
            if abs(CP.PriceMove) > CP.OrderDiff:
                CP.PrevPrice = CP.Price
            self.mylog(DP, data.Time, key.Value, CP.PrevPrice, CP.Price, CP.PriceMove, data[key].Price, 
                    self.Securities[key.Value].Price, self.Portfolio[key.Value].Quantity )

            if abs(CP.PriceMove) < CP.OrderDiff:
                pass
            elif abs(self.Portfolio[key.Value].Quantity) < CP.DefaultUnit:
                OC = "OC:{0}:".format(self.FCC.inc("OC"))
                if CP.DefaultLong == True and CP.LastOpenBuyOrderId == 0: 
                    OrderQty = CP.DefaultUnit
                    OrderPrice = self.formatBuyPrice(CP.Price, CP.OrderDiffPip, CP.OnePip)
                    OrderTag = DP + OC + "OBO:{0}:".format(self.FCC.inc("OBO")) + self.OpenTag + ":F"
                    OT = self.LimitOrder(key.Value, OrderQty, OrderPrice, OrderTag)
                    self.mylog(DP+"HLess OBO OT" , OT.OrderId, OT.Symbol, OT.Quantity, OrderPrice, OT.Time, OT.Status, OT.Tag)
                elif CP.DefaultLong == False and CP.LastOpenSellOrderId == 0:
                    OrderQty = - CP.DefaultUnit
                    OrderPrice = self.formatSellPrice(CP.Price, CP.OrderDiffPip, CP.OnePip)
                    OrderTag = DP + OC + "OSO:{0}:".format(self.FCC.inc("OSO")) + self.OpenTag + ":F"
                    OT = self.LimitOrder(key.Value, OrderQty, OrderPrice, OrderTag)
                    self.mylog(DP+"HLess OSO OT" , OT.OrderId, OT.Symbol, OT.Quantity, OrderPrice, OT.Time, OT.Status, OT.Tag)
#                OT = self.MarketOrder(key.Value, OrderQty, False, OrderTag)
            elif abs(CP.PendingBuy) < CP.MinHolding and abs(CP.PendingSell) > CP.MinHolding and CP.LastOpenSellOrderId == 0:
                # place Open Sell Order
                NextSellPrice = CP.Price + CP.MinProfit
                OrderPrice = self.formatSellPrice(NextSellPrice, CP.OrderDiffPip, CP.OnePip)
                OrderQty = - CP.DefaultUnit
                OC = "OC:{0}:".format(self.FCC.inc("OC"))
                OrderTag = DP + OC + "OSO:{0}:".format(self.FCC.inc("OSO")) + self.OpenTag + ":F"
                OT = self.LimitOrder(key.Value, OrderQty, OrderPrice, OrderTag)
                self.mylog(DP+"PendingBuy Less OT" , OT.OrderId, OT.Symbol, OT.Quantity, OrderPrice, OT.Time, OT.Status, OT.Tag)
            elif abs(CP.PendingSell) < CP.MinHolding and abs(CP.PendingBuy) > CP.MinHolding and CP.LastOpenBuyOrderId == 0:  
                # place Open Buy Order
                NextBuyPrice = CP.Price - CP.MinProfit
                OrderPrice = self.formatBuyPrice(NextBuyPrice, CP.OrderDiffPip, CP.OnePip)
                OrderQty = CP.DefaultUnit
                OC = "OC:{0}:".format(self.FCC.inc("OC"))
                OrderTag = DP + OC + "OBO:{0}:".format(self.FCC.inc("OBO")) + self.OpenTag + ":F"
                OT = self.LimitOrder(key.Value, OrderQty, OrderPrice, OrderTag)
                self.mylog(DP+"PendingSell Less OT" , OT.OrderId, OT.Symbol, OT.Quantity, OrderPrice, OT.Time, OT.Status, OT.Tag)
            
            self.mylog(DP+key.Value, CP.cpName, CP.PrevPrice, CP.Price, CP.PriceMove, CP.PendingBuy, CP.PendingSell,  
                    CP.LastTradeId, CP.LastTradePrice, CP.LastTradeUnit, 
                    CP.LastBuyTradeId, CP.LastOpenBuyOrderId, CP.LastCloseBuyOrderId, CP.LastSellTradeId, 
                    CP.LastOpenSellOrderId, CP.LastCloseSellOrderId,
                    CP.AvgBuyCount, CP.AvgBuyDist, CP.MaxBuyCount, CP.MaxBuyDist, CP.BuyCount, 
                    CP.AvgSellCount, CP.AvgSellDist, CP.MaxSellCount, CP.MaxSellDist, 
                    CP.SellCount, CP.ChngCount, CP.AvgChngDist, CP.MaxChngDist, CP.PlusOverride, 
                    CP.MinusOverride, CP.TakeProfitCount, CP.HoldingUnit, self.Portfolio[key.Value].Quantity  )
            self.Plot('FX Price', CP.cpName, CP.Price )
            self.Plot('PendingBuySell', 'PendingBuy' , CP.PendingBuy )
            self.Plot('PendingBuySell', 'PendingSell' , CP.PendingSell )
            self.Plot('PendingBuySell', 'Holding' , CP.HoldingUnit )
#        self.mylog(DP+"end of onData()")

    def OnOrderEvent(self, OrderEvent):
        OE = "OE:{0}:".format(self.FCC.inc("OE"))
        self.mylog(OE+"param: ", OrderEvent.OrderId, OrderEvent.Symbol, 
                    OrderEvent.Status, OrderEvent.FillPrice, OrderEvent.FillQuantity,
                    OrderEvent.Direction, OrderEvent.Message )
        Order = self.Transactions.GetOrderById(OrderEvent.OrderId)
        OrderTicket = self.Transactions.GetOrderTicket(OrderEvent.OrderId)
        self.mylog(OE+"Order/OTicket: ", OrderTicket.OrderId, Order.BrokerId, 
                Order.Symbol, Order.Price, Order.Quantity, Order.Type, Order.Status, 
                Order.Tag, Order.Direction, Order.Value )

#        otFilter = lambda ot: ( ot.Symbol == OrderEvent.Symbol and self.OpenTag in OrderTicket.Tag )
        OTList = self.Transactions.GetOpenOrders(OrderEvent.Symbol)
        x = 0
        for OO in OTList:
            x += 1
            self.mylog(OE+"OTList: ", x, OO.Id, OO.BrokerId, OO.Symbol, 
                    OO.Price, OO.Quantity, OO.Type, OO.Status, 
                    OO.Tag, OO.Direction, OO.Value ) 

        if OrderEvent.Symbol.Value in self.fxPairs:
            CP = self.fxPairs[OrderEvent.Symbol.Value]
        else:
            self.mylog(OE+"fxPairs[] not found", OrderEvent.Symbol.Value, OrderEvent.OrderId , Order.Id)

        if OrderEvent.Status == OrderStatus.Submitted :
            if Order.Quantity > 0 :  # Buy Submit 
                if  self.OpenTag in Order.Tag:
                    if CP.LastOpenBuyOrderId != 0 and CP.LastOpenBuyOrderId != OrderEvent.OrderId:
                        OT = self.Transactions.GetOrderTicket(CP.LastOpenBuyOrderId)
                        msg = OE + "Canceled OBO-{0} ".format(OT.OrderId)
                        response = OT.Cancel(msg)
                        if response.IsSuccess:
                            self.mylog(OE+"OBO Canceled:" ,  OT.OrderId, OT.Symbol, OT.Quantity, OT.Time, OT.Status, OT.Tag)
                    CP.LastOpenBuyOrderId = OrderEvent.OrderId
                elif self.CloseTag  in Order.Tag:
                    if CP.LastCloseBuyOrderId != 0 and CP.LastCloseBuyOrderId != OrderEvent.OrderId:
                        OT = self.Transactions.GetOrderTicket(CP.LastCloseBuyOrderId)
                        msg = OE + "Canceled CBO-{0} ".format(OT.OrderId)
                        response = OT.Cancel(msg)
                        if response.IsSuccess:
                            self.mylog(OE+"CBO Canceled:" ,  OT.OrderId, OT.Symbol, OT.Quantity, OT.Time, OT.Status, OT.Tag)
                    CP.LastCloseBuyOrderId = OrderEvent.OrderId
            elif Order.Quantity < 0 : # Sell Submit
                if self.OpenTag  in Order.Tag:
                    if CP.LastOpenSellOrderId != 0 and CP.LastOpenSellOrderId != OrderEvent.OrderId:
                        OT = self.Transactions.GetOrderTicket(CP.LastOpenSellOrderId)
                        msg = OE + "Canceled OSO-{0} ".format(OT.OrderId)
                        response = OT.Cancel(msg)
                        if response.IsSuccess:
                            self.mylog(OE+"OSO Canceled:" ,  OT.OrderId, OT.Symbol, OT.Quantity, OT.Time, OT.Status, OT.Tag)
                    CP.LastOpenSellOrderId = OrderEvent.OrderId
                elif self.CloseTag  in Order.Tag:
                    if CP.LastCloseSellOrderId != 0 and CP.LastCloseSellOrderId != OrderEvent.OrderId:
                        OT = self.Transactions.GetOrderTicket(CP.LastCloseSellOrderId)
                        msg = OE + "Canceled CSO-{0} ".format(OT.OrderId)
                        response = OT.Cancel(msg)
                        if response.IsSuccess:
                            self.mylog(OE+"CSO Canceled:" ,  OT.OrderId, OT.Symbol, OT.Quantity, OT.Time, OT.Status, OT.Tag)
                    CP.LastCloseSellOrderId = OrderEvent.OrderId
            self.mylog(OE+"Submitted--LastOrderID", CP.cpName, CP.LastCloseSellOrderId, CP.LastOpenSellOrderId, CP.LastCloseBuyOrderId,
                        CP.LastOpenBuyOrderId)
        # end of Order.status == Submitted 
            
        if OrderEvent.Status == OrderStatus.Filled :
            self.updateCounters(OrderEvent, OrderTicket, OE)
            if CP.LastCloseSellOrderId != 0:
                LastCloseSellOrder = self.Transactions.GetOrderTicket(CP.LastCloseSellOrderId)
            if CP.LastOpenSellOrderId  != 0:
                LastOpenSellOrder = self.Transactions.GetOrderTicket(CP.LastOpenSellOrderId)
            if CP.LastCloseBuyOrderId != 0:
                LastCloseBuyOrder = self.Transactions.GetOrderTicket(CP.LastCloseBuyOrderId)
            if CP.LastOpenBuyOrderId != 0:
                LastOpenBuyOrder = self.Transactions.GetOrderTicket(CP.LastOpenBuyOrderId)

            if OrderEvent.FillQuantity > 0 :  # Buy Fill 
                NextBuyPrice = OrderEvent.FillPrice - CP.OrderDiff
                while NextBuyPrice >= self.Securities[OrderEvent.Symbol].Price :
                    NextBuyPrice -=  CP.OrderDiff

                NextSellPrice = OrderEvent.FillPrice + CP.MinProfit
                while NextSellPrice <= self.Securities[OrderEvent.Symbol].Price :
                    NextSellPrice +=  CP.OrderDiff

                NextBuyPrice = self.formatBuyPrice(NextBuyPrice, CP.OrderDiffPip, CP.OnePip)
                NextSellPrice = self.formatSellPrice(NextSellPrice, CP.OrderDiffPip, CP.OnePip)
                
                self.mylog(OE+"BOF " , OrderEvent.FillPrice, self.Securities[OrderEvent.Symbol].Price, 
#                            CP.OrderDiffPip, CP.OnePip, CP.OrderDiff, CP.MinProfit,
                            NextBuyPrice, NextSellPrice)

                if  self.OpenTag  in Order.Tag:   #Buy - Open - Fill
                    CP.PendingSell -= OrderEvent.FillQuantity    #increase PendingSell
                    CloseSellQuantity = CP.PendingSell / CP.TakeProfitCount
                    OpenBuyQuantity = CP.DefaultUnit
                    if CP.LastOpenBuyOrderId != OrderEvent.OrderId:
                        if CP.LastOpenBuyOrderId != 0:
                            OT = self.Transactions.GetOrderTicket(CP.LastOpenBuyOrderId)
                            msg = OE + "Canceled OBO-{0} ".format(OT.OrderId)
                            response = OT.Cancel(msg)
                            if response.IsSuccess:
                                self.mylog(OE+"OBO Canceled:" ,  OT.OrderId, OT.Symbol, OT.Quantity, OT.Time, OT.Status, OT.Tag)
                        CP.LastOpenBuyOrderId = 0
                    else:
                        CP.LastOpenBuyOrderId = 0
                    if CP.LastCloseSellOrderId != 0:
                        if LastCloseSellOrder.Status == OrderStatus.Submitted :
                            updateSettings = UpdateOrderFields()
                            updateSettings.LimitPrice = NextSellPrice
                            updateSettings.Quantity = CloseSellQuantity
                            OC = "OC:{0}:".format(self.FCC.inc("OC"))
                            updateSettings.Tag = OE + OC + "CSO:{0}:".format(self.FCC.inc("CSO")) + self.CloseTag + ":F"
                            response = LastCloseSellOrder.Update(updateSettings)
                            self.mylog(OE+"BOF-update CSO:", updateSettings.LimitPrice, updateSettings.Quantity, response.ToString() )
                            if response.IsSuccess:
                                OT = LastCloseSellOrder
                                self.mylog(OE+"BOF-CSO:" , OT.OrderId, OT.Symbol, OT.Quantity,
                                             updateSettings.LimitPrice, OT.Time, OT.Status, OT.Tag)

                        else:
                            OC = "OC:{0}:".format(self.FCC.inc("OC"))
                            OrderTag = OE + OC + "CSO:{0}:".format(self.FCC.inc("CSO")) + self.CloseTag + ":F"
                            self.mylog(OE+"BOF-CSO price:" , NextSellPrice , Order.Symbol , CloseSellQuantity, OrderTag )
                            OT1 = self.LimitOrder(Order.Symbol, CloseSellQuantity, NextSellPrice, OrderTag)
                            self.mylog(OE+"BOF-CSO-OT1:" , 
                                    OT1.OrderId, OT1.Symbol, OT1.Quantity, NextSellPrice, OT1.Time, OT1.Status, OT1.Tag)
                            CP.LastCloseSellOrderId = OT1.OrderId
                    else:
                        OC = "OC:{0}:".format(self.FCC.inc("OC"))
                        OrderTag = OE + OC + "CSO:{0}:".format(self.FCC.inc("CSO")) + self.CloseTag + ":F"
                        self.mylog(OE+"BOF-CSO price:" , NextSellPrice , Order.Symbol , CloseSellQuantity )
                        OT1 = self.LimitOrder(Order.Symbol, CloseSellQuantity, NextSellPrice, OrderTag)
                        self.mylog(OE+"BOF-CSO-OT1:" , 
                                OT1.OrderId, OT1.Symbol, OT1.Quantity, NextSellPrice, OT1.Time, OT1.Status, OT1.Tag)
                        CP.LastCloseSellOrderId = OT1.OrderId
                    
                    NextBuyPrice -= CP.OnePip - CP.OnePip
                    OC = "OC:{0}:".format(self.FCC.inc("OC"))
                    OrderTag = OE + OC + "OBO:{0}:".format(self.FCC.inc("OBO")) + self.OpenTag + ":F"    
                    self.mylog(OE+"BOF-OBO price:" , NextBuyPrice , Order.Symbol , OpenBuyQuantity )
                    OT2 = self.LimitOrder(Order.Symbol, OpenBuyQuantity, NextBuyPrice, OrderTag)
                    self.mylog(OE+"BOF-OBO-OT2:" , 
                            OT2.OrderId, OT2.Symbol, OT2.Quantity, NextBuyPrice, OT2.Time, OT2.Status, OT2.Tag)
                    CP.LastOpenBuyOrderId = OT2.OrderId
                         
                elif self.CloseTag  in Order.Tag:        #buy Close
                    CP.PendingBuy -= OrderEvent.FillQuantity      #decrease PendingBuy
                    CloseBuyQuantity = CP.PendingBuy / CP.TakeProfitCount
                    OpenSellQuantity = - CP.DefaultUnit
                    NextSellPrice += CP.OnePip + CP.OnePip
                    if CP.LastCloseBuyOrderId != OrderEvent.OrderId:
                        if CP.LastCloseBuyOrderId != 0:
                            OT = self.Transactions.GetOrderTicket(CP.LastCloseBuyOrderId)
                            msg = OE + "Canceled CBO-{0} ".format(OT.OrderId)
                            response = OT.Cancel(msg)
                            if response.IsSuccess:
                                self.mylog(OE+"CBO Canceled:" ,  OT.OrderId, OT.Symbol, OT.Quantity, OT.Time, OT.Status, OT.Tag)
                        CP.LastCloseBuyOrderId = 0
                    else:
                        CP.LastCloseBuyOrderId = 0
                    if CP.LastOpenSellOrderId != 0:
                        if LastOpenSellOrder.Status == OrderStatus.Submitted :
                            updateSettings = UpdateOrderFields()
                            updateSettings.LimitPrice = NextSellPrice
                            updateSettings.Quantity = OpenSellQuantity
                            OC = "OC:{0}:".format(self.FCC.inc("OC"))
                            updateSettings.Tag = OE + OC + "OSO:{0}:".format(self.FCC.inc("OSO")) + self.OpenTag + ":F"
                            response = LastOpenSellOrder.Update(updateSettings)
                            self.mylog(OE+"BCF-update OSO:", updateSettings.LimitPrice, updateSettings.Quantity, response, response.ToString() )
                            if response.IsSuccess:
                                OT = LastOpenSellOrder
                                self.mylog(OE+"BCF-OSO updated:" ,
                                            OT.OrderId, OT.Symbol, OT.Quantity, updateSettings.LimitPrice, OT.Time, OT.Status, OT.Tag)
                        else:
                            OC = "OC:{0}:".format(self.FCC.inc("OC"))
                            OrderTag = OE + OC + "OSO:{0}:".format(self.FCC.inc("OSO")) + self.OpenTag + ":F"
                            self.mylog(OE+"BCF-OSO price:" , NextSellPrice , Order.Symbol , OpenSellQuantity )
                            OT1 = self.LimitOrder(Order.Symbol, OpenSellQuantity, NextSellPrice, OrderTag)
                            self.mylog(OE+"BCF-OSO-OT1:" , 
                                    OT1.OrderId, OT1.Symbol, OT1.Quantity, NextSellPrice, OT1.Time, OT1.Status, OT1.Tag)
                            CP.LastOpenSellOrderId = OT1.OrderId
                    else:
                        OC = "OC:{0}:".format(self.FCC.inc("OC"))
                        OrderTag = OE + OC + "OSO:{0}:".format(self.FCC.inc("OSO")) + self.OpenTag + ":F"
                        self.mylog(OE+"BCF-OSO price:" , NextSellPrice ,  Order.Symbol , OpenSellQuantity )
                        OT1 = self.LimitOrder(Order.Symbol, OpenSellQuantity, NextSellPrice, OrderTag)
                        self.mylog(OE+"BCF-OSO-OT1:" , 
                                OT1.OrderId, OT1.Symbol, OT1.Quantity, NextSellPrice, OT1.Time, OT1.Status, OT1.Tag)
                        CP.LastOpenSellOrderId = OT1.OrderId
                        
                    OC = "OC:{0}:".format(self.FCC.inc("OC"))
                    OrderTag = OE + OC + "CBO:{0}:".format(self.FCC.inc("CBO")) + self.CloseTag + ":F"    
                    self.mylog(OE+"BCF-CBO price:" , NextBuyPrice ,  Order.Symbol , CloseBuyQuantity )
                    OT2 = self.LimitOrder(Order.Symbol, CloseBuyQuantity, NextBuyPrice, OrderTag)
                    self.mylog(OE+"BCF-CBO-OT2:" , 
                            OT2.OrderId, OT2.Symbol, OT2.Quantity, NextBuyPrice, OT2.Time, OT2.Status, OT2.Tag)
                    CP.LastCloseBuyOrderId = OT2.OrderId
                    
            elif OrderEvent.FillQuantity < 0 : # Sell Fill
                NextBuyPrice = OrderEvent.FillPrice - CP.MinProfit
                while NextBuyPrice >= self.Securities[Order.Symbol].Price :
                    NextBuyPrice -=  CP.OrderDiff

                NextSellPrice = OrderEvent.FillPrice + CP.OrderDiff
                while NextSellPrice <= self.Securities[Order.Symbol].Price :
                    NextSellPrice +=  CP.OrderDiff

                NextBuyPrice = self.formatBuyPrice(NextBuyPrice, CP.OrderDiffPip, CP.OnePip)
                NextSellPrice = self.formatSellPrice(NextSellPrice, CP.OrderDiffPip, CP.OnePip)

                self.mylog(OE+"SOF " , OrderEvent.FillPrice, self.Securities[OrderEvent.Symbol].Price, 
#                            CP.OrderDiffPip, CP.OnePip, CP.OrderDiff, CP.MinProfit,
                            NextBuyPrice, NextSellPrice)

                if  self.OpenTag  in Order.Tag:
                    CP.PendingBuy -= OrderEvent.FillQuantity    #increase PendingBuy
                    CloseBuyQuantity = CP.PendingBuy / CP.TakeProfitCount
                    OpenSellQuantity = -CP.DefaultUnit
                    if CP.LastOpenSellOrderId != OrderEvent.OrderId:
                        if CP.LastOpenSellOrderId != 0:
                            OT = self.Transactions.GetOrderTicket(CP.LastOpenSellOrderId)
                            msg = OE + "Canceled OSO-{0} ".format(OT.OrderId)
                            response = OT.Cancel(msg)
                            if response.IsSuccess:
                                self.mylog(OE+"OSO Canceled:" ,  OT.OrderId, OT.Symbol, OT.Quantity, OT.Time, OT.Status, OT.Tag)
                        CP.LastOpenSellOrderId = 0
                    else:
                        CP.LastOpenSellOrderId = 0
                    if CP.LastCloseBuyOrderId != 0:
                        if LastCloseBuyOrder.Status == OrderStatus.Submitted :
                            updateSettings = UpdateOrderFields()
                            updateSettings.LimitPrice = NextBuyPrice
                            updateSettings.Quantity = CloseBuyQuantity
                            OC = "OC:{0}:".format(self.FCC.inc("OC"))
                            updateSettings.Tag = OE + OC + "CBO:{0}:".format(self.FCC.inc("CBO")) + self.CloseTag + ":F"
                            response = LastCloseBuyOrder.Update(updateSettings)
                            self.mylog(OE+"SOF-CBO update:", updateSettings.LimitPrice, updateSettings.Quantity, response, response.ToString() )
                            if response.IsSuccess:
                                OT = LastCloseBuyOrder
                                self.mylog(OE+"SOF-CBO updated:" , OT.OrderId, OT.Symbol, OT.Quantity,
                                             updateSettings.LimitPrice, OT.Time, OT.Status, OT.Tag)
                        else:
                            OC = "OC:{0}:".format(self.FCC.inc("OC"))
                            OrderTag = OE + OC + "CBO:{0}:".format(self.FCC.inc("CBO")) + self.CloseTag + ":F"    
                            self.mylog(OE+"SOF-CBO price:" , NextBuyPrice , Order.Symbol , CloseBuyQuantity )
                            OT1 = self.LimitOrder(Order.Symbol, CloseBuyQuantity, NextBuyPrice, OrderTag)
                            self.mylog(OE+"SOF-CBO-OT1:" , 
                                    OT1.OrderId, OT1.Symbol, OT1.Quantity, NextBuyPrice, OT1.Time, OT1.Status, OT1.Tag)
                            CP.LastCloseBuyOrderId = OT1.OrderId
                    else:
                        OC = "OC:{0}:".format(self.FCC.inc("OC"))
                        OrderTag = OE + OC + "CBO:{0}:".format(self.FCC.inc("CBO")) + self.CloseTag + ":F"    
                        self.mylog(OE+"SOF-CBO price:" , NextBuyPrice , Order.Symbol , CloseBuyQuantity )
                        OT1 = self.LimitOrder(Order.Symbol, CloseBuyQuantity, NextBuyPrice, OrderTag)
                        self.mylog(OE+"SOF-CBO-OT1:" , 
                                OT1.OrderId, OT1.Symbol, OT1.Quantity, NextBuyPrice, OT1.Time, OT1.Status, OT1.Tag)
                        CP.LastCloseBuyOrderId = OT1.OrderId

                    NextSellPrice += CP.OnePip + CP.OnePip
                    OC = "OC:{0}:".format(self.FCC.inc("OC"))
                    OrderTag = OE + OC + "OSO:{0}:".format(self.FCC.inc("OSO")) + self.OpenTag + ":F"
                    self.mylog(OE+"SOF-OSO price:" , NextSellPrice , Order.Symbol , OpenSellQuantity )
                    OT2 = self.LimitOrder(Order.Symbol, OpenSellQuantity, NextSellPrice, OrderTag)
                    self.mylog(OE+"SOF-OSO-OT2:" , 
                            OT2.OrderId, OT2.Symbol, OT2.Quantity, NextSellPrice, OT2.Time, OT2.Status, OT2.Tag)
                    CP.LastOpenSellOrderId = OT2.OrderId
                         
                elif self.CloseTag  in Order.Tag:
                    CP.PendingSell -= OrderEvent.FillQuantity      #decrease PendingSell
                    CloseSellQuantity = CP.PendingSell / CP.TakeProfitCount
                    OpenBuyQuantity =  CP.DefaultUnit
                    NextBuyPrice -= CP.OnePip - CP.OnePip
                    if CP.LastCloseSellOrderId != OrderEvent.OrderId:
                        if CP.LastCloseSellOrderId != 0:
                            OT = self.Transactions.GetOrderTicket(CP.LastCloseSellOrderId)
                            msg = OE + "Canceled CSO-{0} ".format(OT.OrderId)
                            response = OT.Cancel(msg)
                            if response.IsSuccess:
                                self.mylog(OE+"CSO Canceled:" ,  OT.OrderId, OT.Symbol, OT.Quantity, OT.Time, OT.Status, OT.Tag)
                        CP.LastCloseSellOrderId = 0
                    else:
                        CP.LastCloseSellOrderId = 0
                    if CP.LastOpenBuyOrderId != 0:
                        if LastOpenBuyOrder.Status == OrderStatus.Submitted :
                            updateSettings = UpdateOrderFields()
                            updateSettings.LimitPrice = NextBuyPrice
                            updateSettings.Quantity = OpenBuyQuantity
                            OC = "OC:{0}:".format(self.FCC.inc("OC"))
                            updateSettings.Tag = OE + OC + "OBO:{0}:".format(self.FCC.inc("OBO")) + self.OpenTag + ":F"
                            response = LastOpenBuyOrder.Update(updateSettings)
                            self.mylog(OE+"SCF-OBO update:", updateSettings.LimitPrice, updateSettings.Quantity, response, response.ToString() )
                            if response.IsSuccess:
                                OT = LastOpenBuyOrder
                                self.mylog(OE+"SCF-OBO updated:" ,
                                            OT.OrderId, OT.Symbol, OT.Quantity, updateSettings.LimitPrice, OT.Time, OT.Status, OT.Tag)
                        else:
                            OC = "OC:{0}:".format(self.FCC.inc("OC"))
                            OrderTag = OE + OC + "OBO:{0}:".format(self.FCC.inc("OBO")) + self.OpenTag + ":F"    
                            self.mylog(OE+"SCF-OBO price:" , NextBuyPrice ,  Order.Symbol , OpenBuyQuantity )
                            OT1 = self.LimitOrder(Order.Symbol, OpenBuyQuantity, NextBuyPrice, OrderTag)
                            self.mylog(OE+"SCF-OBO-OT1:" , 
                                    OT1.OrderId, OT1.Symbol, OT1.Quantity, NextBuyPrice, OT1.Time, OT1.Status, OT1.Tag)
                            CP.LastOpenBuyOrderId = OT1.OrderId
                    else:
                        OC = "OC:{0}:".format(self.FCC.inc("OC"))
                        OrderTag = OE + OC + "OBO:{0}:".format(self.FCC.inc("OBO")) + self.OpenTag + ":F"    
                        self.mylog(OE+"SCF-OBO price:" , NextBuyPrice ,  Order.Symbol , OpenBuyQuantity )
                        OT1 = self.LimitOrder(Order.Symbol, OpenBuyQuantity, NextBuyPrice, OrderTag)
                        self.mylog(OE+"SCF-OBO-OT1:" , 
                                OT1.OrderId, OT1.Symbol, OT1.Quantity, NextBuyPrice, OT1.Time, OT1.Status, OT1.Tag)
                        CP.LastOpenBuyOrderId = OT1.OrderId

                    OC = "OC:{0}:".format(self.FCC.inc("OC"))
                    OrderTag = OE + OC + "CSO:{0}:".format(self.FCC.inc("CSO")) + self.CloseTag + ":F"
                    self.mylog(OE+"SCF-CSO price:" , NextSellPrice , Order.Symbol , CloseSellQuantity )
                    OT2 = self.LimitOrder(Order.Symbol, CloseSellQuantity, NextSellPrice, OrderTag)
                    self.mylog(OE+"SCF-CSO-OT2: " , 
                            OT2.OrderId, OT2.Symbol, OT2.Quantity, NextSellPrice, OT2.Time, OT2.Status, OT2.Tag)
                    CP.LastCloseSellOrderId = OT2.OrderId
            
            self.mylog(OE+"END of onOrderEvent()--Filled")
        # end of Order.status == Filled
        self.mylog(OE+CP.cpName, CP.cpName, self.Securities[OrderEvent.Symbol].Price, CP.PendingBuy, CP.PendingSell,  
                CP.LastTradeId, CP.LastTradePrice, CP.LastTradeUnit, 
                CP.LastBuyTradeId, CP.LastOpenBuyOrderId, CP.LastCloseBuyOrderId, CP.LastSellTradeId, 
                CP.LastOpenSellOrderId, CP.LastCloseSellOrderId,
                CP.AvgBuyCount, CP.AvgBuyDist, CP.MaxBuyCount, CP.MaxBuyDist, CP.BuyCount, 
                CP.AvgSellCount, CP.AvgSellDist, CP.MaxSellCount, CP.MaxSellDist, 
                CP.SellCount, CP.ChngCount, CP.AvgChngDist, CP.MaxChngDist, CP.PlusOverride, 
                CP.MinusOverride, CP.TakeProfitCount, CP.HoldingUnit )