Git Product home page Git Product logo

Comments (9)

r-neri avatar r-neri commented on September 15, 2024

Hello jnritter86 please could you post your entire code of botstrategy.py.
Thank you

from trading-bot.

jnritter86 avatar jnritter86 commented on September 15, 2024

I have a whole decision tree ready to go, but it assumes MACD returns a list from which I can pick elements, and I took everything but the first level out in an effort to see where it was breaking. It seems to run into trouble passing values from MACD to the EMA function in botindicators.py:

`from botlog import BotLog
from botindicators import BotIndicators
from bottrade import BotTrade
from datetime import datetime

class BotStrategy(object):
    def __init__(self):
	self.output = BotLog()
	self.prices = []
	self.closes = [] # Needed for Momentum Indicator
	self.trades = []
	self.currentPrice = ""
	self.currentClose = ""
	self.numSimulTrades = 1
	self.indicators = BotIndicators()

def tick(self,candlestick):
	self.currentPrice = float(candlestick.priceAverage)
	self.prices.append(self.currentPrice)
	
	#self.currentClose = float(candlestick['close'])
	#self.closes.append(self.currentClose)
	
	self.output.log("DateTime: "+ str(datetime.utcfromtimestamp(candlestick.startTime).strftime("%Y-%b-%d %H:%M:%S"))+"\tPrice: "+str(candlestick.priceAverage)+"\tMoving Average: "+str(self.indicators.movingAverage(self.prices,15)))

	self.evaluatePositions()
	self.updateOpenTrades()
	self.showPositions()

def evaluatePositions(self):
	openTrades = []
	for trade in self.trades:
		if (trade.status == "OPEN"):
			openTrades.append(trade)

	if (len(openTrades) < self.numSimulTrades):
                    if (self.indicators.MACD(self.prices)[2] > 0):
		#if (self.currentPrice < self.indicators.movingAverage(self.prices,15)): # switch to MACD based strategy - moving average versus current price is a dumb strategy.
			self.trades.append(BotTrade(self.currentPrice,stopLoss=self.currentPrice *.001)) #should add a better calculation to create dynamic stop loss later

	for trade in openTrades:
                    if (self.indicators.MACD(self.prices)[2] < 0):
		#if (self.currentPrice > self.indicators.movingAverage(self.prices,15)):
			trade.close(self.currentPrice)

def updateOpenTrades(self):
	for trade in self.trades:
		if (trade.status == "OPEN"):
			trade.tick(self.currentPrice)

def showPositions(self):
	for trade in self.trades:
		trade.showTrade()`

from trading-bot.

r-neri avatar r-neri commented on September 15, 2024

Hello jnRitter86
I resolve the problem in line 22
a[:period] = a[period]

Change the botindicators.py to

import numpy as np

and change all numpy to np on the other lines.

Happy code !
Rogério.

from trading-bot.

MisterZogs avatar MisterZogs commented on September 15, 2024

Hello,
Numpy is not the problem here. jnritter86 I have the same issue trying to use EMA, I'll have a more deep look at it. Let's tell each other if anyone finds the solution.

from trading-bot.

r-neri avatar r-neri commented on September 15, 2024

misterZogs you are correct.

from trading-bot.

r-neri avatar r-neri commented on September 15, 2024

What this line of code does?
a[:period] = a[period]

from trading-bot.

potajedehabichuelas avatar potajedehabichuelas commented on September 15, 2024

The problem comes when there aren't enough points to perform the calculation of the EMA, therefore when trying to access the "period" component it crashes as prices doesn't have enough components.

To solve it I've added an if check at the beginning and it would simply return 0 when there isn't enough data to calculate the EMA

def EMA(self, prices, period):
	if (len(prices) <= period):
		return 0

	x = numpy.asarray(prices)
	weights = None
	weights = numpy.exp(numpy.linspace(-1., 0., period))
	weights /= weights.sum()

	a = numpy.convolve(x, weights, mode='full')[:len(x)]
	a[:period] = a[period]
	return a

I think that should do without messing up anything (I just started looking at the repository :P)

from trading-bot.

jnritter86 avatar jnritter86 commented on September 15, 2024

potajedehabichuelas I tried a similar technique, but now the bot runs until it hits period 13 (one period after the default for nfast in the MACD function) and then crashes with the same error. There's got to be something I'm missing about the function.

from trading-bot.

potajedehabichuelas avatar potajedehabichuelas commented on September 15, 2024

@jnritter86 It doesn't crash for me, but maybe there is something to do with your code in BotStrategy or something else (mine is modified). I've also updated some functions in my indicators file, since I thought it's best not to calculate a MACD or EMA if there isn't enough data to avoid anything that could confuse the strategy.

This is the code with the changes so far:

def movingAverage(self, prices, period):
	if (len(prices) > 1):
		return sum(prices[-period:]) / float(len(prices[-period:]))

def EMA(self, prices, period):

	if (len(prices) <= period):
		return

	x = numpy.asarray(prices)
	weights = None
	weights = numpy.exp(numpy.linspace(-1., 0., period))
	weights /= weights.sum()

	a = numpy.convolve(x, weights, mode='full')[:len(x)]
	a[:period] = a[period]
	return a

def MACD(self, prices, nslow=26, nfast=12):
	emaslow = self.EMA(prices, nslow)
	emafast = self.EMA(prices, nfast)

	if not (emafast is None or emaslow is None):
		return emaslow, emafast, emafast - emaslow

Just be careful as if there is not enough data it would return 'None' which will crash the thing :P

from trading-bot.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.