Overall Statistics
Total Trades
0
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Net Profit
0%
Sharpe Ratio
0
Probabilistic Sharpe Ratio
0%
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0
Beta
0
Annual Standard Deviation
0
Annual Variance
0
Information Ratio
-21.044
Tracking Error
0.103
Treynor Ratio
0
Total Fees
$0.00
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Data.Market import *
from QuantConnect.Data.Consolidators import *
from datetime import timedelta

import numpy as np
import pandas as pd
import statsmodels.formula.api as sm
from scipy import stats
import datetime as datetime
from datetime import datetime
from math import floor

class Forex(QCAlgorithm):
    
    def Initialize(self):
        self.SetStartDate(2020, 1, 1) 
        self.SetEndDate(2020, 1, 2) 
        self.SetCash(1000000)
        
        
        self.eur = self.AddFuture(Futures.Currencies.EUR)
        self.eur.SetFilter(timedelta(2), timedelta(90))
        self.SetWarmup(30)
        
        self.renkoATR = self.ATR(self.eur.Symbol, (6*24), MovingAverageType.T3, Resolution.Minute)
        
        self.wil = self.WILR(self.eur.Symbol,15,Resolution.Minute)
        
        ## Dictionary to store the consolidators by contract symbol -- allows us to access them in other methods
        self.renkoConsolidators = {}
        
        ## RENKO Area
        renkoPlot = Chart("Renko Plot")
        renkoPlot.AddSeries(Series("RenkoBar", SeriesType.Bar, 0))
        self.AddChart(renkoPlot)
        
        # Widen the free portfolio percentage to 30% to avoid margin calls for futures
        self.Settings.FreePortfolioValuePercentage = 0.30
        
        
        # Wait 30 min to warm up; close out 30 min for market close for this future
        # Set the schedules for when we trade futures
        self.Schedule.On(self.DateRules.Every(DayOfWeek.Sunday), self.TimeRules.AfterMarketOpen(self.eur.Symbol, 60), self.OpeningBar)
        self.Schedule.On(self.DateRules.Every(DayOfWeek.Friday), self.TimeRules.BeforeMarketClose(self.eur.Symbol, 60), self.ClosingBar)
        
        # Setting a risk management model
        self.SetRiskManagement(TrailingStopRiskManagementModel(0.08))
        
    
    def OnSecuritiesChanged(self, changes):
        for security in changes.AddedSecurities:
            #prevent the SPY from getting handlers; since we'll want this as bench mark
            if security.Symbol == "SPY":
                continue
            
            history = self.History(security.Symbol, 5, Resolution.Minute).sort_index(level='time', ascending=False)[:3]
            
            for index, row in history.iterrows():
                self.Debug("History: " + str(index[1]) + ": " + index[2].strftime("%m/%d/%Y %I:%M:%S %p") + " > " + str(row.close))
                
            ##How do we load this into ATR?    
                        
            consolidator = RenkoConsolidator(2.5)  ## Should be the ATR value being passed in here.
            consolidator.DataConsolidated += self.HandleRenkoBar  ## Define the handler function
            self.SubscriptionManager.AddConsolidator(security.Symbol, consolidator)  ## Add the consolidator to our main data handler
            self.renkoConsolidators[security.Symbol] = consolidator  ## Add consolidator to the dictionary, indexed by symbol
            #Do we need to add the indicator here, Init, or Event Handler?
            
        for security in changes.RemovedSecurities:
            consolidator = self.renkoConsolidators.pop(security.Symbol)  ## Remove/assign consolidator
            self.SubscriptionManager.RemoveConsolidator(security.Symbol, consolidator)  ## Remove the consolidator from our data handler to keep memory usage low
            consolidator.DataConsolidated -= self.HandleRenkoBar  ## Remove handler function
            
    
    def HandleRenkoBar(self, sender, consolidated):
        #self.Plot("Renko Plot", "RenkoBar", consolidated.Close)
        #self.Plot("Renko Plot", "enko Volume", consolidated.Volume)
        #self.Debug(f"7BAR - {consolidated.Time} - {consolidated.Open} {consolidated.Close}")
        
        self.Debug(f"Direction - {consolidated.Time} - {consolidated.Direction}")
        # if self.Portfolio.Invested:
        #     self.Liquidate(consolidated.Symbol)
        
        
    def OpeningBar(self):
        self.Debug(f"Futures markets are now open For US: {self.Time} DING! DING! DING!")
        # might need to load the history here
    
    def ClosingBar(self):
        self.Debug(f"Futures markets are now CLOSED: {self.Time} and ALL POSITION CLOSED")
        self.Liquidate()
    
        
    def OnMarginCallWarning(self):
        self.Error("You received a margin call warning..")
        
    
    def OnEndOfDay(self):
        self.Log(f"OnEndOfDay: {self.Time}")
        #Log the end of day prices:
        #self.Plot("Trade Plot", "Price", self.lastPrice)  
    
    def OnData(self, slice):
        if self.Portfolio.Invested: 
            return
        
        #We'll want to filter to only those contracts we're following...
        
        for chain in slice.FutureChains:
            for contract in chain.Value:
                self.Debug("{0},Bid={1} Ask={2} Last={3} OI={4}".format(
                        contract.Symbol.Value,
                        contract.BidPrice,
                        contract.AskPrice,
                        contract.LastPrice,
                        contract.OpenInterest))