Overall Statistics
Total Trades
875
Average Win
0.01%
Average Loss
-0.01%
Compounding Annual Return
-98.686%
Drawdown
5.000%
Expectancy
-0.753
Net Profit
-4.966%
Sharpe Ratio
-13.836
Loss Rate
85%
Win Rate
15%
Profit-Loss Ratio
0.60
Alpha
-1.625
Beta
0.609
Annual Standard Deviation
0.184
Annual Variance
0.034
Information Ratio
-6.719
Tracking Error
0.155
Treynor Ratio
-4.168
Total Fees
$0.00
# this is incomplete attempt to conver c# file to python. coarse funciton incomplete.
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")
AddReference("QuantConnect.Indicators")
from System import *
from QuantConnect import *
from System.Linq import *
from QuantConnect.Indicators import *
from QuantConnect.Data.Market import *
from System.Collections.Concurrent import *
from QuantConnect.Data.UniverseSelection import *
from QuantConnect.Indicators.CandlestickPatterns import *
from datetime import timedelta, datetime
import numpy
import sys
import decimal
import talib





class TestCandlestickAlgorithm ( QCAlgorithm):
    
    def Initialize(self):
        self.VERBOSEMODE = True
        self.VERBOSEMODE2 = True            
        self.SetCash(100000)
        self.SetStartDate(2019,8,4)
        self.SetEndDate(2019,8,6)
        self.SetBrokerageModel(BrokerageName.OandaBrokerage)
        
        self.security= self.AddForex("EURUSD", Resolution.Minute, Market.Oanda)
        #self.security = self.AddEquity("SPY", Resolution.Minute)
        self.symbol = self.security.Symbol
        self.symbolStr = self.symbol.Value
        periods = decimal.Decimal(10)
        self.pattern = Doji(self.symbol)
        self.SetWarmUp(timedelta(days=10))
        #self.cdl = CandleHelper(self)
        self.tryOnce = True
        self.doji = CandleDoji(self,'doji', 1)
        res = Resolution.Minute
        self.sellAfterBars = 5 # how many bars to wait before exiting
        self.barCounter = 0
 
        plotter =Chart("Plotter");
        plotter.AddSeries(Series("EURUSD", SeriesType.Line,0))
        self.AddChart(plotter)
 
 
    def OnData(self,slice):
        self.Log("Time: {}" . format(slice.Time) )

        if (self.IsWarmingUp): 
            self.barCounter = 0
            return
        self.barCounter += 1
        if self.Securities[self.symbolStr].Invested and self.barCounter > self.sellAfterBars :
            self.SetHoldings(self.symbolStr,0)
            self.Log("Closing out after {} bars".format( self.sellAfterBars ) )
            self.barCounter = 0
            return
               
        if slice is None:
            self.Log("no slice " )
            self.barCounter -= 1        
            return
            
        try:
            #self.Log("self.symbol {} of type {} self.symbolStr {} of type {}" . format(self.symbol,type(self.symbol), self.symbolStr,  type(self.symbolStr) ) )
            #self.Log("self pattern is {} " . format(self.pattern))
            fxQuoteBars = slice.QuoteBars
            qb = fxQuoteBars['EURUSD']     ## EURUSD QuoteBar
            #self.Log(" qb {} of type {} open {}   high {} low {} close {} time {} " . format(qb, type(qb),qb.Open,qb.High, qb.Low, qb.Close, qb.Time ))
            
            '''
            op =  numpy.array([12.33])
            hi = numpy.array([13.33])
            lo =  numpy.array([11.33])
            cl =  numpy.array([12.33])
            self.Log("set up test array vars ok e.g. cl {}" .format(cl))         

            test = talib.CDLDOJI(op,hi,lo,cl )
            self.Log("got here  ok to test {} ". format(test))          
            '''          
            
            
            self.doji.Update(qb)
            self.Log("self.doji is {} at time {}" . format(self.doji.Value,self.doji.Time))
            
            if self.doji.Value:
                self.Log("Time: {} doji found with value {} going long symbol {}" . format( slice.Time, self.doji.Value, self.symbol) )
                self.SetHoldings(self.symbol, 1)
            else:
                self.Log("no doji recognized skipping")        
        except:
            self.Log('An unknown error occurred trying OnData' +  str(sys.exc_info()[0]) )               

        
class CandleDoji:
    #we are createing a doji indicator made up of o/h/l/c of bar
    # self.doji = CandleDoji('doji', 1)
    # self.RegisterIndicator("SPY", self.doji, Resolution.Minute)

    def __init__(self,algo,name,period):
        self.Name = name
        self.Time = datetime.min
        self.Value = False        
        self.IsReady = False        
        self.Open = None
        self.High = None
        self.Low = None
        self.Close = None
        self.symbol = algo.symbol
        self.algo = algo
        self.algo.Log('CandleDoji initiated for symbol {}' .format(self.symbol))
        self.adjustFactor = float(0.20) # percentage of overall candle height by which you want body of candle to be inferior to
        self.minCandleHeight = float(0.00) # if you want to eliminate candles smaller than a given size set this value to number of basis points
        
    def __repr__(self):
        return "{0} -> IsReady: {1}. Time: {2}. Value: {3}".format(self.Name, self.IsReady, self.Time, self.Value)
    

        
    def Update(self,input):
        #Doji is a candlestick pattern which is a candle of specific shape: its Open price is equal (or almost equal) to the Close price. The candle 
        #is considered Doji if the difference between its Open and Close prices does not exceed average body height multiplied by the specified factor.
       
        try:       
            self.Open= numpy.array([input.Open])     
            self.Close= numpy.array([input.Close])
            
            self.High= numpy.array([input.High])
            self.Low= numpy.array([input.Low])
            self.Time = numpy.array([input.EndTime ])  

            candleBars = talib.CDLDOJI(self.Open,self.High,self.Low,self.Close)
            #self.algo.Log("got here past CDLDOJI ok")
            if self.algo.VERBOSEMODE: self.algo.Log('CandleDoji testing for Open {} Hi {}  Low {} Close {} Time {}'. format(self.Open,self.High,self.Low,self.Close, self.Time))

            body = abs(self.Open - self.Close)
            self.algo.Log("body of candle measures {} " . format(body))
            cdlHeight =  abs(self.High-self.Low)

            self.algo.Log("height of candle measures {} " . format(cdlHeight))
            maxBody = float(cdlHeight) * self.adjustFactor
            bodyAsPct = float(body )/ float(cdlHeight)
            isDoji = (body < maxBody ) and (cdlHeight > self.minCandleHeight)
            
            self.algo.Log(" doji? {} if body {} < maxBody {} current body is  {} as percent of candle  and candle height {} > {}" . format(isDoji ,body, maxBody,bodyAsPct,cdlHeight,self.minCandleHeight))
            self.Value = isDoji
            self.IsReady = True
            self.algo.Log("CandleDoji is ready with value {}" .format(self.Value) )

            '''
            #if self.algo.VERBOSEMODE: self.algo.Log('CandleDoji candleBars of type () count {}  items {}'. format(type(candleBars), len(candleBars),candleBars) )
            self.algo.Log("my doji definition ? " . format(self.isDoji(input)))
            candleBarSum = sum(candleBars)
            #candleBarSum  is of type numpy.int64 which as a scalar must be converted with item to be converted to decimal type   
            self.Value = decimal.Decimal(candleBarSum.item()) 
            '''
        except:
            self.Value = False
            self.IsReady = False
            self.algo.Log('An unknown error occurred trying CandleDoji' +  str(sys.exc_info()[0]) )