Overall Statistics
Total Trades
202
Average Win
7.52%
Average Loss
-3.23%
Compounding Annual Return
-0.462%
Drawdown
39.500%
Expectancy
0.055
Net Profit
-1.268%
Sharpe Ratio
0.169
Loss Rate
68%
Win Rate
32%
Profit-Loss Ratio
2.33
Alpha
0.036
Beta
1.231
Annual Standard Deviation
0.365
Annual Variance
0.133
Information Ratio
0.115
Tracking Error
0.355
Treynor Ratio
0.05
Total Fees
$0.00
import numpy as np
import decimal
from datetime import datetime
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
### <summary>
### Basic template algorithm simply initializes the date range and cash. This is a skeleton
### framework you can use for designing an algorithm.
### </summary>
class BasicTemplateAlgorithm(QCAlgorithm):
    
    def Initialize(self):
        self.SetStartDate(2016,1,1)  #Set Start Date
        self.SetEndDate(2018,10,1)    #Set End Date
        self.SetCash(50000)           #Set Strategy Cash
        self.forex = self.AddForex("EURUSD", Resolution.Hour, Market.Oanda)
        self.load_symbols()
        self.SetBenchmark("EURUSD")
        
        for symbol in self.symbols:
            self.MovingAverageConvergenceDivergence = self.MACD(symbol, 9, 20, 9, MovingAverageType.Exponential, Resolution.Hour)
            
            fast_period = 5
            slow_period = 27
            self.fast = self.EMA(symbol, fast_period)
            self.slow = self.EMA(symbol, slow_period)
            
            overlayPlot = Chart("Overlay Plot")
            overlayPlot.AddSeries(Series("EURUSD", SeriesType.Line, 0))
            overlayPlot.AddSeries(Series("Buy", SeriesType.Scatter, 0))
            overlayPlot.AddSeries(Series("Sell", SeriesType.Scatter, 0))
            #overlayPlot.AddSeries(Series("MACD", SeriesType.Line, 1))
            overlayPlot.AddSeries(Series("MACD_Signal", SeriesType.Line, 1))
            overlayPlot.AddSeries(Series("EMA", SeriesType.Line, 2))
            overlayPlot.AddSeries(Series("EMA_slow", SeriesType.Line, 2))
            self.AddChart(overlayPlot)
            
            self.SetWarmup(slow_period)  
            self.first = True
    def OnData(self, data):
        for symbol in self.symbols:
            if not self.MovingAverageConvergenceDivergence.IsReady: 
                return
            
            # get the indicator value 
            if self.first and not self.IsWarmingUp:
                self.first = False
            
            #define a small tolerance on our checks to avoid bouncing?
            tolerance = 0.00015
            intolerance = 0.00005
            signalDeltaPercent = self.MovingAverageConvergenceDivergence.Signal.Current.Value 
            current = data[symbol].Value
            
            highVector = decimal.Decimal(1.0019)
            lowVector = decimal.Decimal(0.9995)
            buy_signal_triggered, sell_signal_triggered = False, False
            
            #Tradingtimes
            '''start = timestamp(st_yr_inp, st_mn_inp, st_dy_inp,10,00)
            end = timestamp(en_yr_inp, en_mn_inp, en_dy_inp,14,00)
            can_trade = time >= start and time <= end'''
    
            if not self.Portfolio.Invested:
                if self.Portfolio.Invested <= 0:
                    if (self.fast.Current.Value * highVector) < self.slow.Current.Value and signalDeltaPercent > tolerance: #downtrend, go short
                        #set stop price and limit price at +-2%
                        onePercent = decimal.Decimal(1.00217)
                        takeProfit = decimal.Decimal(0.9994)
                        twoPercent = decimal.Decimal(1.00261)
                        allocation = decimal.Decimal(10)
                        
                        invested = self.Portfolio.TotalPortfolioValue * allocation
                        #self.MarketOrder(symbol, -invested)
                        
                        self.Debug(self.Portfolio.TotalPortfolioValue)
                        
                        #Buy stop limit , stop price should be lower than limit price
                        stopPrice = self.Securities[symbol].Price * onePercent
                        limitPrice = self.Securities[symbol].Price * takeProfit
                        stopLimit = self.Securities[symbol].Price * twoPercent
                        #self.Debug("signalDeltaPercent is " + str(signalDeltaPercent))
                        
                        #sell shares if SL/TP is reached
                        self.StopLimitOrder(symbol, invested, stopPrice, stopLimit)
                        self.LimitOrder(symbol, -invested, limitPrice)
                        sell_signal_triggered = True
                if not self.Portfolio.Invested:
                    if (self.fast.Current.Value * lowVector) > self.slow.Current.Value and signalDeltaPercent < -tolerance: #uptrend, Go Long
                        #set stop price and limit price at +-2%
                        onePercent = decimal.Decimal(0.99773)
                        takeProfit = decimal.Decimal(1.001)
                        twoPercent = decimal.Decimal(0.99817) #0.99817 25pips
                        allocation = decimal.Decimal(10)
                        
                        invested = self.Portfolio.TotalPortfolioValue * allocation
                        #self.MarketOrder(symbol, invested)
                        
                        #Buy stop limit , stop price should be lower than limit price
                        stopPrice = self.Securities[symbol].Price * onePercent
                        limitPrice = self.Securities[symbol].Price * takeProfit
                        stopLimit = self.Securities[symbol].Price * twoPercent
                        
                        #sell shares if SL/TP
                        self.StopLimitOrder(symbol, -invested, stopPrice, stopLimit)
                        self.LimitOrder(symbol, invested, limitPrice)
                        buy_signal_triggered = True
                  
            if self.Portfolio.Invested:       
                if self.Portfolio[symbol].IsLong:
                    if self.fast < self.slow and signalDeltaPercent > intolerance:
                        
                        self.Liquidate(symbol)
                        
                if self.Portfolio[symbol].IsShort:
                    if self.fast > self.slow and signalDeltaPercent < -intolerance:
                        
                        self.Liquidate(symbol)
                        
            if buy_signal_triggered:
                    self.Plot("Overlay Plot", "Buy", current)
            elif sell_signal_triggered:
                self.Plot("Overlay Plot", "Sell", current)
            self.Plot("Overlay Plot", "EURUSD", current)
            self.Plot("Overlay Plot", "MACD_Signal", float(self.MovingAverageConvergenceDivergence.Signal.Current.Value))
            self.Plot("Overlay Plot", "EMA", self.fast.Current.Value)
            self.Plot("Overlay Plot", "EMA_slow", self.slow.Current.Value)
    
    def load_symbols(self) :
        syl_list = [
            'EURUSD',
            #'USDCAD',
            #'AUDUSD',
            #'USDJPY',
        ]
        
        self.symbols = []
        for i in syl_list:
            self.symbols.append(self.AddForex(i, Resolution.Hour, Market.Oanda).Symbol)