def end(self, lastCandle, allCandles): print("Last tick") accountInfo = self.fxcm.getAccountInfo() Graph.setTitle("Final Account Equity: {} / ExampleStrategy".format( accountInfo['equity'])) Graph.addIndicator(x=allCandles.index.to_pydatetime(), y=Indicator.ema(allCandles['askclose'], 20), name='EMA 20', color="rgba(0, 255, 0, 0.6)")
def getBbTrending(self, bb, nextCandle): newBbTrending = self.isTrending(bb['askbb']) if self.bbTrending == None or self.bbTrending != newBbTrending: print("TREND CHANGE") self.bbTrending = newBbTrending Graph.addAction(nextCandle.name, bb['askbb']['mid'][-1], 0, 'TRENDING' if newBbTrending else 'TRENDLESS', True if newBbTrending else False, 1) Graph.addAction(nextCandle.name, bb['bidbb']['mid'][-1], 0, 'TRENDING' if newBbTrending else 'TRENDLESS', True if newBbTrending else False, 2)
def closePosition(self, positionId): """Close a position by his Id Args: positionId (int): Id of the position """ position = self.getOpenPosition(positionId) self.__account['balance'] += position.get_grossPL() self.__account['usdMr'] -= position.get_usedMargin() self.__openPositions.remove(position) self.__closePositions.append(FxcmBacktestClosePosition(position)) self.__updateAccountInfo() isBuy = position.get_isBuy() Graph.addAction( self.__getLastCandle().name, position.get_close(), 'Close #' + str(positionId) + ' (' + str(round(position.get_grossPL(), 2)) + ')', isBuy, 2 if isBuy else 1) return True
def __openPosition(self, isBuy, amount, limit, stop): lastCandle = self.__getLastCandle() if not utils.checkLimitStopViability(limit, stop): print( "ERROR: Can't open position: Limit or Stop value is incorrect") return None newTradeId = len(self.__openPositions) + len(self.__closePositions) newPosition = FxcmBacktestOpenPosition(self, lastCandle, newTradeId, self.__forexPair, isBuy, amount, limit, stop) if self.__account['usableMargin'] - (newPosition.get_usedMargin() * amount * 2) < 0: print("ERROR: Can't open position: Not enough usable margin.") return None self.__account['usdMr'] += newPosition.get_usedMargin() Graph.addAction(lastCandle.name, newPosition.get_open(), 'Open #' + str(newTradeId), isBuy, 1 if isBuy else 2) self.__openPositions.append(newPosition) return newPosition.get_tradeId()
def end(self, lastCandle, allCandles): print("Last tick") accountInfo = self.fxcm.getAccountInfo() Graph.setTitle( "Final Account Equity: {} : {}% / Strategy: DoubleEMA".format(accountInfo['equity'], ((accountInfo['equity'] - self.startEquity) / self.startEquity) * 100)) Graph.addIndicator( x=allCandles.index.to_pydatetime(), y=Indicator.ema(allCandles['askclose'], self.emaShortPeriod), name='EMA {}'.format(self.emaShortPeriod), color="rgba(255, 0, 0, 0.6)" ) Graph.addIndicator( x=allCandles.index.to_pydatetime(), y=Indicator.ema(allCandles['askclose'], 50), name='EMA {}'.format(self.emaLongPeriod), color="rgba(0, 0, 255, 0.6)" ) Graph.addIndicator( x=allCandles.index.to_pydatetime(), y=Indicator.ema(allCandles['bidclose'], self.emaShortPeriod), name='EMA {}'.format(self.emaShortPeriod), color="rgba(255, 0, 0, 0.6)", plot=2 ) Graph.addIndicator( x=allCandles.index.to_pydatetime(), y=Indicator.ema(allCandles['bidclose'], 50), name='EMA {}'.format(self.emaLongPeriod), color="rgba(0, 0, 255, 0.6)", plot=2 )
def detectCrossOverWindows(self, lastCandle, allCandles): emaShort = Indicator.ema(allCandles['askclose'][-self.emaShortPeriod:], self.emaShortPeriod)[-1] emaLong = Indicator.ema(allCandles['askclose'][-self.emaLongPeriod:], self.emaLongPeriod)[-1] emaBidShort = Indicator.ema(allCandles['bidclose'][-self.emaShortPeriod:], self.emaShortPeriod)[-1] emaBidLong = Indicator.ema(allCandles['bidclose'][-self.emaLongPeriod:], self.emaLongPeriod)[-1] if (self.lastEmaLong == 0 or self.lastBidEmaLong == 0): self.lastEmaShort = emaShort self.lastEmaLong = emaLong self.lastBidEmaShort = emaBidShort self.lastBidEmaLong = emaBidLong return crossedUp = (self.lastEmaShort < self.lastEmaLong and emaShort > emaLong) crossedDown = (self.lastBidEmaShort > self.lastBidEmaLong and emaBidShort < emaBidLong) distance = (lastCandle['askclose'] - emaShort) * 100000 if (crossedUp): self.upTrendWindow = 1 Graph.addAction( lastCandle.name, emaShort, 'Crossed UP - {}'.format(distance), None, 1) if (crossedDown): self.upTrendWindow = -1 # Sell if crossing is bearish. if (len(self.fxcm.getOpenPositions('list')) > 0): pos = self.fxcm.getOpenPositions('list')[0] self.fxcm.closePosition(pos['tradeId']) Graph.addAction( lastCandle.name, emaBidShort, 'Crossed Down', None, 2) if (self.upTrendWindow > 0 and emaShort <= lastCandle['askclose'] and emaLong <= lastCandle['askclose']): self.upTrendWindow += 1 # Reset if price is lower than the emaLong. (Detect changing trend) if (emaLong > lastCandle['askclose']): self.upTrendWindow = 0 # Reset if trend window was opened, but difference between indicators is not strong for confirmation distance = (lastCandle['askclose'] - emaShort) * 100000 if (self.upTrendWindow > 0 and distance < 12): self.upTrendWindow = 0 Graph.addAction( lastCandle.name, lastCandle['askclose'], 'Ignored Trend - {}'.format(distance), None, 1) self.lastEmaShort = emaShort self.lastEmaLong = emaLong self.lastBidEmaShort = emaBidShort self.lastBidEmaLong = emaBidLong
def set_edge_list(self, edge_list: list): """Permite generar un grafo a partir de una lista de conexiones. Parameters ---------- edge_list : List Lista de caminos en forma de tuplas [(0, 1), (1, 2)] """ self.__edge_list = edge_list nodes_list_aux = [] for x, y in edge_list: nodes_list_aux.append(x) if y: nodes_list_aux.append(y) self.__nodes = len({node for node in nodes_list_aux}) self.graph = Graph(self.__edge_list)
def lastTick(self, lastCandle, allCandles): self.fxcm.closePositions() self.end(lastCandle, allCandles) Graph.addCandleSticks(x=allCandles.index.to_pydatetime(), open=allCandles['askopen'], high=allCandles['askhigh'], low=allCandles['asklow'], close=allCandles['askclose'], name='Ask Candles ') Graph.addCandleSticks(x=allCandles.index.to_pydatetime(), open=allCandles['bidopen'], high=allCandles['bidhigh'], low=allCandles['bidlow'], close=allCandles['bidclose'], name='Bid Candles ', plot=2) Graph.render()
def __generate_graph(self): """Genera la lista de caminos y el grafo a partir de este. """ self.__matrix_to_edges() self.graph = Graph(self.__edge_list)
def __init__(self, device, num_class, dropout, train_phase=True, num_joints=25): super(Generator, self).__init__() ############################## ####GRAPHS INITIALIZATIONS#### ############################## cols1 = [15, 16, 1, 3, 6, 9, 12, 11, 22, 19, 14] cols2 = [0, 4, 6] cols3 = [0] self.graph25 = Graph(25, [(0, 1), (1, 8), (2, 1), (3, 2), (4, 3), (5, 1), (6, 5), (7, 6), (9, 8), (10, 9), (11, 10), (22, 11), (23, 22), (24, 11), (12, 8), (13, 12), (14, 13), (21, 14), (19, 14), (20, 19), (17, 15), (15, 0), (16, 0), (18, 16)], 1) self.ca25 = torch.tensor(self.graph25.A, dtype=torch.float32, requires_grad=False).to(device) self.a25 = torch.tensor(self.graph25.getA(cols1), dtype=torch.float32, requires_grad=False).to(device) _, l1 = self.graph25.getLowAjd(cols1) self.graph11 = Graph(11, l1, 0) self.ca11 = torch.tensor(self.graph11.A, dtype=torch.float32, requires_grad=False).to(device) self.a11 = torch.tensor(self.graph11.getA(cols2), dtype=torch.float32, requires_grad=False).to(device) _, l2 = self.graph11.getLowAjd(cols2) self.graph3 = Graph(3, l2, 0) self.ca3 = torch.tensor(self.graph3.A, dtype=torch.float32, requires_grad=False).to(device) self.a3 = torch.tensor(self.graph3.getA(cols3), dtype=torch.float32, requires_grad=False).to(device) _, l3 = self.graph3.getLowAjd(cols3) self.graph1 = Graph(1, l3, 0) self.ca1 = torch.tensor(self.graph1.A, dtype=torch.float32, requires_grad=False).to(device) ############################## #############END############## ############################## self.num_class = num_class self.num_joints = num_joints self.device = device self.train_phase = train_phase self.embed = nn.Embedding(self.num_class, 512) self.tanh = nn.Tanh() self.softmax = nn.Softmax(dim=1) self.lrelu = nn.LeakyReLU() self.relu = nn.ReLU() self.sigmoid = torch.nn.Sigmoid() self.dropout = nn.Dropout(dropout) self.act = self.lrelu self.norm1 = nn.BatchNorm2d(256) self.norm2 = nn.BatchNorm2d(128) self.norm3 = nn.BatchNorm2d(64) self.norm4 = nn.BatchNorm2d(32) self.norm5 = nn.BatchNorm2d(16) ########STGCN####### self.gcn0 = st_gcn(1024, 512, (1, self.ca1.size(0))) self.gcn1 = st_gcn(512, 256, (1, self.ca3.size(0))) self.gcn2 = st_gcn(256, 128, (1, self.ca3.size(0))) self.gcn3 = st_gcn(128, 64, (3, self.ca11.size(0))) self.gcn4 = st_gcn(64, 32, (3, self.ca11.size(0))) self.gcn5 = st_gcn(32, 16, (7, self.ca25.size(0))) self.gcn6 = st_gcn(16, 2, (7, self.ca25.size(0))) #########END########## #######GRAPH-UPSAMPLING######## self.ups1 = UpSampling(1, 3, self.a3, 1024) self.ups2 = UpSampling(3, 11, self.a11, 256) self.ups3 = UpSampling(11, 25, self.a25, 64) ###############END############## #######TEMPORAL-UPSAMPLING######## self.upt1 = nn.ConvTranspose2d(256, 256, (2, 1), stride=(2, 1)) self.upt2 = nn.ConvTranspose2d(128, 128, (2, 1), stride=(2, 1)) self.upt3 = nn.ConvTranspose2d(64, 64, (2, 1), stride=(2, 1)) self.upt4 = nn.ConvTranspose2d(32, 32, (2, 1), stride=(2, 1))
class Generator(nn.Module): def __init__(self, device, num_class, dropout, train_phase=True, num_joints=25): super(Generator, self).__init__() ############################## ####GRAPHS INITIALIZATIONS#### ############################## cols1 = [15, 16, 1, 3, 6, 9, 12, 11, 22, 19, 14] cols2 = [0, 4, 6] cols3 = [0] self.graph25 = Graph(25, [(0, 1), (1, 8), (2, 1), (3, 2), (4, 3), (5, 1), (6, 5), (7, 6), (9, 8), (10, 9), (11, 10), (22, 11), (23, 22), (24, 11), (12, 8), (13, 12), (14, 13), (21, 14), (19, 14), (20, 19), (17, 15), (15, 0), (16, 0), (18, 16)], 1) self.ca25 = torch.tensor(self.graph25.A, dtype=torch.float32, requires_grad=False).to(device) self.a25 = torch.tensor(self.graph25.getA(cols1), dtype=torch.float32, requires_grad=False).to(device) _, l1 = self.graph25.getLowAjd(cols1) self.graph11 = Graph(11, l1, 0) self.ca11 = torch.tensor(self.graph11.A, dtype=torch.float32, requires_grad=False).to(device) self.a11 = torch.tensor(self.graph11.getA(cols2), dtype=torch.float32, requires_grad=False).to(device) _, l2 = self.graph11.getLowAjd(cols2) self.graph3 = Graph(3, l2, 0) self.ca3 = torch.tensor(self.graph3.A, dtype=torch.float32, requires_grad=False).to(device) self.a3 = torch.tensor(self.graph3.getA(cols3), dtype=torch.float32, requires_grad=False).to(device) _, l3 = self.graph3.getLowAjd(cols3) self.graph1 = Graph(1, l3, 0) self.ca1 = torch.tensor(self.graph1.A, dtype=torch.float32, requires_grad=False).to(device) ############################## #############END############## ############################## self.num_class = num_class self.num_joints = num_joints self.device = device self.train_phase = train_phase self.embed = nn.Embedding(self.num_class, 512) self.tanh = nn.Tanh() self.softmax = nn.Softmax(dim=1) self.lrelu = nn.LeakyReLU() self.relu = nn.ReLU() self.sigmoid = torch.nn.Sigmoid() self.dropout = nn.Dropout(dropout) self.act = self.lrelu self.norm1 = nn.BatchNorm2d(256) self.norm2 = nn.BatchNorm2d(128) self.norm3 = nn.BatchNorm2d(64) self.norm4 = nn.BatchNorm2d(32) self.norm5 = nn.BatchNorm2d(16) ########STGCN####### self.gcn0 = st_gcn(1024, 512, (1, self.ca1.size(0))) self.gcn1 = st_gcn(512, 256, (1, self.ca3.size(0))) self.gcn2 = st_gcn(256, 128, (1, self.ca3.size(0))) self.gcn3 = st_gcn(128, 64, (3, self.ca11.size(0))) self.gcn4 = st_gcn(64, 32, (3, self.ca11.size(0))) self.gcn5 = st_gcn(32, 16, (7, self.ca25.size(0))) self.gcn6 = st_gcn(16, 2, (7, self.ca25.size(0))) #########END########## #######GRAPH-UPSAMPLING######## self.ups1 = UpSampling(1, 3, self.a3, 1024) self.ups2 = UpSampling(3, 11, self.a11, 256) self.ups3 = UpSampling(11, 25, self.a25, 64) ###############END############## #######TEMPORAL-UPSAMPLING######## self.upt1 = nn.ConvTranspose2d(256, 256, (2, 1), stride=(2, 1)) self.upt2 = nn.ConvTranspose2d(128, 128, (2, 1), stride=(2, 1)) self.upt3 = nn.ConvTranspose2d(64, 64, (2, 1), stride=(2, 1)) self.upt4 = nn.ConvTranspose2d(32, 32, (2, 1), stride=(2, 1)) ###############END############## def forward(self, y, z): #batch,channels,time,vertex ######CONDITIONING######### if self.train_phase: emb = self.embed(y).view(len(z), 512, 1, 1).repeat(1, 1, z.shape[2], 1) inp = torch.cat((z, emb), 1) else: ######TESTING CODE########## emb = self.embed(y).unsqueeze(2).repeat(1, 1, 4).permute( 1, 0, 2).reshape(len(z), 512, -1, 1) inp = torch.cat((z[:, :, :emb.shape[2]], emb), 1) ########################### ################################ aux = self.lrelu(self.gcn0(inp, self.ca1)) inp = aux aux = self.act(self.norm1(self.gcn1(self.ups1(inp), self.ca3))) aux = self.dropout( self.act(self.norm2(self.gcn2(self.upt1(aux), self.ca3)))) aux = self.act( self.norm3(self.gcn3(self.ups2(self.upt2(aux)), self.ca11))) aux = self.dropout( self.act(self.norm4(self.gcn4(self.upt3(aux), self.ca11)))) aux = self.act( self.norm5(self.gcn5(self.ups3(self.upt4(aux)), self.ca25))) aux = self.gcn6(aux, self.ca25) return aux
def __init__(self, device, num_class, size_sample, num_joints=25): super(Discriminator, self).__init__() ############################## ####GRAPHS INITIALIZATIONS#### ############################## cols1 = [15, 16, 1, 3, 6, 9, 12, 11, 22, 19, 14] cols2 = [0, 4, 6] cols3 = [0] self.graph25 = Graph(25, [(0, 1), (1, 8), (2, 1), (3, 2), (4, 3), (5, 1), (6, 5), (7, 6), (9, 8), (10, 9), (11, 10), (22, 11), (23, 22), (24, 11), (12, 8), (13, 12), (14, 13), (21, 14), (19, 14), (20, 19), (17, 15), (15, 0), (16, 0), (18, 16)], 1) self.ca25 = torch.tensor(self.graph25.A, dtype=torch.float32, requires_grad=False).to(device) self.a25 = torch.tensor(self.graph25.getA(cols1), dtype=torch.float32, requires_grad=False).to(device) _, l1 = self.graph25.getLowAjd(cols1) self.graph11 = Graph(11, l1, 0) self.ca11 = torch.tensor(self.graph11.A, dtype=torch.float32, requires_grad=False).to(device) self.a11 = torch.tensor(self.graph11.getA(cols2), dtype=torch.float32, requires_grad=False).to(device) _, l2 = self.graph11.getLowAjd(cols2) self.graph3 = Graph(3, l2, 0) self.ca3 = torch.tensor(self.graph3.A, dtype=torch.float32, requires_grad=False).to(device) self.a3 = torch.tensor(self.graph3.getA(cols3), dtype=torch.float32, requires_grad=False).to(device) _, l3 = self.graph3.getLowAjd(cols3) self.graph1 = Graph(1, l3, 0) self.ca1 = torch.tensor(self.graph1.A, dtype=torch.float32, requires_grad=False).to(device) ############################## #############END############## ############################## self.size_sample = size_sample self.num_joints = num_joints self.device = device self.num_class = num_class self.embed = nn.Embedding(self.num_class, self.num_joints) self.tanh = nn.Tanh() self.softmax = nn.Softmax(dim=1) self.lrelu = nn.LeakyReLU() self.relu = nn.ReLU() self.sigmoid = torch.nn.Sigmoid() self.dropout = nn.Dropout() self.act = self.lrelu self.norm1 = nn.BatchNorm2d(64) self.norm2 = nn.BatchNorm2d(128) self.norm3 = nn.BatchNorm2d(256) ########STGCN####### self.gcn0 = st_gcn(3, 2, (7, self.ca25.size(0))) self.gcn1 = st_gcn(2, 32, (7, self.ca25.size(0))) self.gcn2 = st_gcn(32, 64, (3, self.ca11.size(0))) self.gcn3 = st_gcn(64, 128, (3, self.ca11.size(0))) self.gcn4 = st_gcn(128, 256, (1, self.ca3.size(0))) self.gcn5 = st_gcn(256, 1, (1, self.ca1.size(0))) #########END########## #######GRAPH-DOWNSAMPLING######## self.dws1 = DownSampling(25, 11, self.a25, 64) self.dws2 = DownSampling(11, 3, self.a11, 256) self.dws3 = DownSampling(3, 1, self.a3, 1) ###############END############## #######TEMPORAL-DOWNSAMPLING######## self.dwt1 = nn.Conv2d(32, 32, (int(self.size_sample / 2) + 1, 1)) self.dwt2 = nn.Conv2d(64, 64, (int(self.size_sample / 4) + 1, 1)) self.dwt3 = nn.Conv2d(128, 128, (int(self.size_sample / 8) + 1, 1)) self.dwt4 = nn.Conv2d(256, 256, (int(self.size_sample / 16) + 1, 1)) self.dwt5 = nn.Conv2d(1, 1, (int(self.size_sample / 16), 3))
def tick(self, nextCandle, allCandles): if allCandles.shape[0] < self.BB_PERIOD: return askBbCandles = allCandles['askclose'][-self.BB_PERIOD:] bidBbCandles = allCandles['bidclose'][-self.BB_PERIOD:] bb = dict({ 'askbb': Indicator.bb(askBbCandles, self.BB_PERIOD), 'bidbb': Indicator.bb(bidBbCandles, self.BB_PERIOD) }) lastBbSqueezing = self.bbSqueezing bbWidth = bb['askbb']['up'][-1] - bb['askbb']['low'][-1] self.bbSqueezing = bbWidth <= self.bbSqueezeWidth if self.bbSqueezing == True and lastBbSqueezing == True: # Add duration to bb Squeeze self.bbSqueezeDuration += 1 elif self.bbSqueezing == False and lastBbSqueezing == True: # Break duration of bb Squeeze self.bbSqueezeDuration = 0 if self.bbTrending != 'no': # If trending, Look for end of trending if (self.bbTrending == 'down' and self.isPriceAboveBbMid(nextCandle['askclose'], bb['askbb']['mid'])) or \ (self.bbTrending == 'up' and self.isPriceUnderBbMid(nextCandle['askclose'], bb['askbb']['mid'])): self.bbTrending = 'no' Graph.addAction(nextCandle.name, bb['askbb']['mid'][-1], 'TREENDLESS', False, 1) Graph.addAction(nextCandle.name, bb['bidbb']['mid'][-1], 'TREENDLESS', False, 2) else: # If not trending if self.isAnyPositionOpen(): # Look for closing position position = self.fxcm.getOpenPositions('list')[0] if (position['isBuy'] and self.isPriceAboveBbMid(nextCandle['askclose'], bb['askbb']['mid'])) or \ (not position['isBuy'] and self.isPriceUnderBbMid(nextCandle['bidclose'], bb['bidbb']['mid'])): self.fxcm.closePosition(position['tradeId']) else: if self.isPriceAboveBbUp(nextCandle['askclose'], bb['askbb']['up']): # If squeezing and squeeze duration not too long if self.bbSqueezing == True and self.bbSqueezeDuration <= self.BB_SQUEEZE_MAX_DURATION: self.bbTrending = 'up' print("TREND UP") Graph.addAction(nextCandle.name, bb['askbb']['mid'][-1], 'TRENDING UP', True, 1) Graph.addAction(nextCandle.name, bb['bidbb']['mid'][-1], 'TRENDING UP', True, 2) else: print("SELL") stopLimit = self.getStop(bb['askbb']['up'][-1], bb['askbb']['low'][-1]) self.fxcm.sell(self.getMaxAmount(), stop=-stopLimit, limit=stopLimit) elif self.isPriceUnderBbLow(nextCandle['bidclose'], bb['bidbb']['low']): # If squeezing and squeeze duration not too long if self.bbSqueezing == True and self.bbSqueezeDuration <= self.BB_SQUEEZE_MAX_DURATION: self.bbTrending = 'down' print("TREND DOWN") Graph.addAction(nextCandle.name, bb['askbb']['mid'][-1], 'TRENDING DOWN', True, 1) Graph.addAction(nextCandle.name, bb['bidbb']['mid'][-1], 'TRENDING DOWN', True, 2) else: print("BUY") stopLimit = self.getStop(bb['bidbb']['up'][-1], bb['bidbb']['low'][-1]) self.fxcm.buy(self.getMaxAmount(), stop=-stopLimit, limit=stopLimit)
def end(self, lastCandle, allCandles): accountInfo = self.fxcm.getAccountInfo() Graph.setTitle("Final Account Equity: {} / BBStrategy".format( accountInfo['equity'])) askbb = Indicator.bb(allCandles['askclose'], self.BB_PERIOD) Graph.addIndicator(x=allCandles.index.to_pydatetime(), y=askbb['up'], name='Ask BBup ', color="rgba(0, 0, 255, 0.6)") Graph.addIndicator(x=allCandles.index.to_pydatetime(), y=askbb['mid'], name='Ask BBmid', color="rgba(0, 0, 200, 0.5)") Graph.addIndicator(x=allCandles.index.to_pydatetime(), y=askbb['low'], name='Ask BBlow', color="rgba(0, 0, 180, 0.4)") bidbb = Indicator.bb(allCandles['bidclose'], self.BB_PERIOD) Graph.addIndicator(x=allCandles.index.to_pydatetime(), y=bidbb['up'], name='Bid BBup ', color="rgba(0, 0, 255, 0.6)", plot=2) Graph.addIndicator(x=allCandles.index.to_pydatetime(), y=bidbb['mid'], name='Bid BBmid', color="rgba(0, 0, 200, 0.5)", plot=2) Graph.addIndicator(x=allCandles.index.to_pydatetime(), y=bidbb['low'], name='Bid BBlow', color="rgba(0, 0, 180, 0.4)", plot=2)