Overall Statistics
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(2018,3,20)  #Set Start Date
        self.SetEndDate(2018,9,20)    #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 = 25 #was 27 but i am trying to test my indicators
            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.0015
            #intolerance = 0.00005
            signalDeltaPercent = self.MovingAverageConvergenceDivergence.Signal.Current.Value 
            current = data[symbol].Value
            
            highVector = decimal.Decimal(1.0015)
            lowVector = decimal.Decimal(0.9995)
            buy_signal_triggered, sell_signal_triggered = False, False
            
            
    
            if not self.Portfolio.Invested:
                if self.Portfolio.Invested <= 500000:
                    if (self.fast.Current.Value * lowVector) < 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.99617) #raised this from 99617 to try to increase profits
                        twoPercent = decimal.Decimal(1.00261) #was 1.00261
                        allocation = decimal.Decimal(6)
                        invested = self.Portfolio.TotalPortfolioValue * allocation
                        #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))
                        
                        self.MarketOrder(symbol, -invested)
                        #self.LimitOrder(symbol, invested, limitPrice)
                        #self.Debug(self.Portfolio.TotalPortfolioValue)
                        self.StopMarketOrder(symbol, invested, stopLimit) #verified it works because my losses didn't exceed 2.5% a day
                        
                        
                        sell_signal_triggered = True
            if not self.Portfolio.Invested:
                if self.Portfolio.Invested <= 500000:
                    if (self.fast.Current.Value * highVector) > 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.00461) #raised this from 00461 to try to increase profits
                        twoPercent = decimal.Decimal(0.99897) #was 0.99897 and i was getting 0.00248 pips/0.07% loss days
                        allocation = decimal.Decimal(6)
                        invested = self.Portfolio.TotalPortfolioValue * allocation
                        #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.MarketOrder(symbol, invested)
                        #self.LimitOrder(symbol, -invested, limitPrice)
                        #sell shares if SL/TP
                        self.StopMarketOrder(symbol, -invested, stopLimit)  #verified it works because my losses didn't exceed 2.5% a day
                        
                        buy_signal_triggered = True
                  
            if self.Portfolio.Invested:
                highVector = decimal.Decimal(1.005)
                lowVector = decimal.Decimal(0.9994)
                if self.Portfolio[symbol].IsLong:
                    if (self.fast.Current.Value * lowVector) < self.slow.Current.Value: # and signalDeltaPercent > 0:
                        
                        self.Liquidate(symbol)
                        
                if self.Portfolio[symbol].IsShort:
                    if (self.fast.Current.Value * highVector) > self.slow.Current.Value: # and signalDeltaPercent < 0:
                        
                        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',
            #'USDCHF',
        ]
        
        self.symbols = []
        for i in syl_list:
            self.symbols.append(self.AddForex(i, Resolution.Hour, Market.Oanda).Symbol)