对象没有属性,但也没有定义全局名称

时间:2017-11-22 22:35:15

标签: python attributes

我正在尝试从文本文件中提取一个变量来在交易机器人算法中进行数学运算。

这是我的代码。我已缩短它以解决问题:

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

class BotStrategy(object):
  def __init__(self):
    self.output = BotLog()
    self.prices = []
    self.closes = [] # Needed for Momentum Indicator
    self.trades = []                #20 trades at 0.021 =  .042 
    self.currentPrice = ""      #after a day, add the BTC to 0.042 and adjust simultaneous trades
    self.currentClose = ""      #53 coins for 2500 simul trades per coin pair
    self.numSimulTrades = 100   #looks like dash ends at 2500 trades  eth ends at about     1000 trades total for all four would be about 208 coins
    self.indicators = BotIndicators()
    mid=0

    with open('test.txt', 'r') as myfile:
        mid=myfile.read().replace('\n', '')
        self.output.log(mid)
    mid=int(mid)

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("Price: "+str(candlestick.priceAverage)+"\tMoving Average: "+str(self.indicators.movingAverage(self.prices,5)))
    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.currentPrice) < self.indicators.movingAverage(self.prices,15)):
            self.trades.append(BotTrade(self.currentPrice,stopLoss=.0001))

    for trade in openTrades:
        if ((self.currentPrice + mid) > 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()

使用“self.mid”我收到错误:'Bot1'对象没有属性'mid' 如果我删除了“self”,我得到:NameError:全局名称'mid'未定义

我做错了什么?我正在失去理智!

请求回溯:这是无属性:

user@user1:~/Desktop/bot/part3$ python backtest.py
90
Price: 0.0486309    Moving Average: None
Price: 0.04853957   Moving Average: 0.048585235
Trade opened
Entry Price: 0.04853957 Status: OPEN Exit Price: 
Price: 0.04847643   Moving Average: 0.0485489666667
Trade opened
Traceback (most recent call last):
  File "backtest.py", line 15, in <module>
    main(sys.argv[1:])
  File "backtest.py", line 12, in main
    strategy.tick(candlestick)
  File "/home/user/Desktop/bot/part3/botstrategy.py", line 30, in tick
    self.evaluatePositions()
  File "/home/user/Desktop/bot/part3/botstrategy.py", line 46, in evaluatePositions
    self.currentPrice= float(self.currentPrice+self.mid)
AttributeError: 'BotStrategy' object has no attribute 'mid'

这是“中期”未定义:

user@user1:~/Desktop/bot/part3$ python backtest.py
90
Price: 0.0486309    Moving Average: None
Price: 0.04853957   Moving Average: 0.048585235
Trade opened
Entry Price: 0.04853957 Status: OPEN Exit Price: 
Price: 0.04847643   Moving Average: 0.0485489666667
Trade opened
Traceback (most recent call last):
  File "backtest.py", line 15, in <module>
    main(sys.argv[1:])
  File "backtest.py", line 12, in main
    strategy.tick(candlestick)
  File "/home/user/Desktop/bot/part3/botstrategy.py", line 30, in tick
    self.evaluatePositions()
  File "/home/user/Desktop/bot/part3/botstrategy.py", line 46, in    evaluatePositions
    if ((self.currentPrice + mid) >     self.indicators.movingAverage(self.prices,15)) :
    NameError: global name 'mid' is not defined

bottrade.py代码:

from botlog import BotLog
import botstrategy 

def main(argv):
    currentMovingAverage = 0;
    tradePlaced = False
    typeOfTrade = False
    dataDate = ""
    orderNumber = ""
    dataPoints = []
    localMax = []
    currentResistance = 0.018
    mid = int(mid)


class BotTrade(object):
    def __init__(self,currentPrice,stopLoss=0):
        self.output = BotLog()
        prices = []
        self.status = "OPEN"
        self.entryPrice = currentPrice
        self.exitPrice = ""
     self.output.log("Trade opened")


        if (stopLoss):
            self.stopLoss = currentPrice - stopLoss

    def close(self,currentPrice):
    self.mid = int(mid)
     if currentPrice > (self.entryPrice + self.mid): #DASH likes about 0.000937, XRP about 0.000001, ETH likes  0.000855  XMR likes  0.000396
          #use ETH to start with, with less than 4 trades. you get about 1.7 BTC in a week - 4 trades @ 0.021=0.084 BTC. Daily is 0.24 
            self.status = "CLOSED"
            self.exitPrice = currentPrice
            self.output.log("Trade closed")

    def tick(self, currentPrice):
        if (self.stopLoss):
            if (currentPrice < self.stopLoss):
                self.close(currentPrice)


    def showTrade(self):
         tradeStatus = "Entry Price: "+str(self.entryPrice)+" Status: "+str(self.status)+" Exit Price: "+str(self.exitPrice)

        if (self.status == "CLOSED"):
            tradeStatus = tradeStatus + " Profit:! "
            if (self.exitPrice > self.entryPrice):
                tradeStatus = tradeStatus + " \033[92m"
            else:
                tradeStatus = tradeStatus + " \033[91m"

        tradeStatus = tradeStatus+str(abs((self.exitPrice) - (self.entryPrice)))+" \033[0m"

    self.output.log(tradeStatus)

来自bottrade.py的回溯

user@user1:~/Desktop/bot/part3$ python backtest.py
Price: 1131.71486314    Moving Average: None
Price: 1103.73203402    Moving Average: 1117.72344858
Trade opened
Entry Price: 1103.73203402 Status: OPEN Exit Price: 
Price: 1108.36463027    Moving Average: 1114.60384248
Trade opened
Traceback (most recent call last):
  File "backtest.py", line 15, in <module>
    main(sys.argv[1:])
   File "backtest.py", line 12, in main
     strategy.tick(candlestick)
   File "/home/user/Desktop/bot/part3/botstrategy.py", line 29, in tick
self.evaluatePositions()
      File "/home/user/Desktop/bot/part3/botstrategy.py", line 46, in evaluatePositions
    trade.close(self.currentPrice)
    File "/home/user/Desktop/bot/part3/bottrade.py", line 30, in close
self.mid = int(mid)
NameError: global name 'mid' is not defined

现在全面展示。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

运行时系统是正确的。在mid案例中,mid中没有定义变量evaluatePositions。同样,mid的实例没有对象属性BotStrategy。看一下初始化的区别:

class BotStrategy(object):
  def __init__(self):
    self.output = BotLog()
    self.prices = []
    self.closes = [] # Needed for Momentum Indicator
    ...
    mid=int(mid)

mid init 的局部变量,而不是属性。也许你需要

    self.mid = int(mid)

并在您引用该值时使用self.mid

这对你有用吗?