stocktsats Stoch RSI values dont match with trading view values - stochastic

def good_buying_condition_stoch_ema_ema(the_exchange, symbol, timeframe):
#print ("finding the good to go long/buy signal")
r = dict();
hist_data = get_historical_data(the_exchange, symbol, timeframe)
stock_data = create_stock(hist_data) #stock stats data
stock_data.KDJ_WINDOW=14
stock_data.KDJ_PARAM=(3.0 / 14.0, 3.0 / 14.0)
#stock_data._calc_kd(stock_data['close']);
stock_data.MACD_EMA_SHORT = 50
stock_data.MACD_EMA_LONG = 200
macd = stock_data._get_macd(stock_data)
gap = stock_data['kdjk'][499] - stock_data['kdjd'][499]
abs_gap = abs(gap);
r['datetime'] = stock_data['timestamp'][499]
r['symbol'] = symbol
r['timeframe'] = timeframe
r['close'] = stock_data['close'][499]
r['kdjk3'] = stock_data['kdjk_3'][499]
r['kdjd3'] = stock_data['kdjd_3'][499]
r['kdjk'] = stock_data['kdjk'][499]
r['kdjd'] = stock_data['kdjd'][499]
r['macd'] = stock_data['macd'][499]
stock_data.KDJ_WINDOW=7
stock_data._calc_kd(stock_data['close']);
r['kdjk7'] = stock_data['kdjk_7'][499]
r['kdjd7'] = stock_data['kdjd_7'][499]
stock_data.KDJ_WINDOW=14
stock_data._calc_kd(stock_data['close']);
r['kdjk14'] = stock_data['kdjk_14'][499]
r['kdjd14'] = stock_data['kdjd_14'][499]
if (gap < 1 and gap > -1): r['side'] = 'HODL'
elif (gap > 1): r['side'] = 'buy'
elif (gap < -1): r['side'] = 'sell'
else: r['side'] = 'unknown'
if (r['side'] == "buy"):
if (stock_data['kdjk'][499] < 20): r['confidence'] = "strong"
elif (stock_data['kdjk'][499] < 75): r['confidence'] = "ok"
elif (stock_data['kdjk'][499] < 80): r['confidence'] = "questionable"
elif (stock_data['kdjk'][499] < 90): r['confidence'] = "risky"
elif (stock_data['kdjk'][499] < 100): r['confidence'] = "extreme risk"
elif (r['side'] == "sell"):
if (stock_data['kdjk'][499] < 20): r['confidence'] = "extreme risk"
elif (stock_data['kdjk'][499] < 40): r['confidence'] = "risky"
elif (stock_data['kdjk'][499] < 60): r['confidence'] = "questionable"
elif (stock_data['kdjk'][499] < 80): r['confidence'] = "ok"
elif (stock_data['kdjk'][499] < 100): r['confidence'] = "strong"
else: r['confidence'] = 'unknown'
r['momentum'] = gap
if (stock_data['macd'][499] > 0 and stock_data['macd'][499] < 1):
r['trend'] = "bullish"
elif (stock_data['macd'][499] > 1 ):
r['trend'] = "uncertain"
elif (stock_data['macd'][499] < 0 ):
r['trend'] = "bearish"
#### FINTA tech indicators
#ohlc = resample(hist_data, "1m")
#ema50 = TA.EMAIndicator(close=hist_data.close, n=50)
#hist_data['ema50_tpj'] = ema50
#print ("TA.STOCH K = ", TA.STOCH(hist_data['close'], period=14)[499])
#print ("TA.STOCH D = ", TA.STOCHD(hist_data['close'], period=3, stoch_period=14)[499])
#print ("TA.EMA 9 = ", TA.EMA(hist_data)[499])
#print ("TA.EMA 50 = ", TA.EMA(hist_data, 50)[499])
#print ("TA.EMA 200 = ", TA.EMA(hist_data, 200)[499])
r['ta_ema9'] = TA.EMA(hist_data)[499]
r['ta_ema50'] = TA.EMA(hist_data, 50)[499]
r['ta_ema200'] = TA.EMA(hist_data, 200)[499]
r['ta_atr14'] = TA.ATR(hist_data, 14)[499]
r['atr14'] = stock_data['atr'][499]
r['min14'] = hist_data.close.rolling(14).min()[499];
r['max14'] = hist_data.close.rolling(14).max()[499];
print ("returning", r)
return r
def get_historical_data(exchange, coin_pair, timeframe):
"""Get Historical data (ohlcv) from a coin_pair
"""
# optional: exchange.fetch_ohlcv(coin_pair, '1h', since)
data = exchange.fetch_ohlcv(coin_pair, timeframe)
# update timestamp to human readable timestamp
data = [[exchange.iso8601(candle[0])] + candle[1:] for candle in data]
header = ['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume']
df = pd.DataFrame(data, columns=header)
return df
def create_stock(historical_data):
"""Create StockData from historical data using stockstats
"""
stock = Sdf.retype(historical_data)
return stock
in a 10 second loop, the above produces the following output:
returning {'datetime': '2021-05-26T15:55:00.000Z', 'symbol': 'XRP/USDT', 'timeframe': '1m', 'close': 0.9838, 'kdjk3': 23.00115833047544, 'kdjd3': 33.246639262609804, 'kdjk': 31.557468092520086, 'kdjd': 40.89122272232644, 'macd': -0.00016899252758151295, 'kdjk7': 29.02460416563654, 'kdjd7': 40.37714935820455, 'kdjk14': 31.502465082807905, 'kdjd14': 41.35215340927536, 'side': 'sell', 'confidence': 'risky', 'momentum': -9.333754629806354, 'trend': 'bearish', 'ta_ema9': 0.9863129810243016, 'ta_ema50': 0.9876962538671861, 'ta_ema200': 0.9980103854792317, 'ta_atr14': 0.003885714285714286, 'atr14': 0.0038138082006646855, 'min14': 0.9827, 'max14': 0.9927}
returning {'datetime': '2021-05-26T15:56:00.000Z', 'symbol': 'XRP/USDT', 'timeframe': '1m', 'close': 0.9831, 'kdjk3': 14.450607500341013, 'kdjd3': 26.42224572620021, 'kdjk': 23.26053428390232, 'kdjd': 34.77728953914806, 'macd': -0.000447425790014111, 'kdjk7': 18.859864087371616, 'kdjd7': 32.94481190275474, 'kdjk14': 23.223865610760864, 'kdjd14': 35.07235377273352, 'side': 'sell', 'confidence': 'risky', 'momentum': -11.516755255245737, 'trend': 'bearish', 'ta_ema9': 0.9856063848194415, 'ta_ema50': 0.9875009374853446, 'ta_ema200': 0.9978533449719774, 'ta_atr14': 0.0036571428571428666, 'atr14': 0.0035699647577600697, 'min14': 0.9827, 'max14': 0.9927}
baseCurrBal: 556.21882609 percent: .4 ticker['last']: 0.984
returning {'datetime': '2021-05-26T15:56:00.000Z', 'symbol': 'XRP/USDT', 'timeframe': '1m', 'close': 0.9838, 'kdjk3': 20.006163055896863, 'kdjd3': 28.27409757805216, 'kdjk': 25.127200950569065, 'kdjd': 35.399511761370306, 'macd': -0.00039158533417382735, 'kdjk7': 20.88884959461808, 'kdjd7': 33.62114040517023, 'kdjk14': 25.09053227742761, 'kdjd14': 35.69457599495577, 'side': 'sell', 'confidence': 'risky', 'momentum': -10.27231081080124, 'trend': 'bearish', 'ta_ema9': 0.9857463848194415, 'ta_ema50': 0.9875283884657932, 'ta_ema200': 0.9978603573934625, 'ta_atr14': 0.003707142857142861, 'atr14': 0.003619964757760064, 'min14': 0.9827, 'max14': 0.9927}
returning {'datetime': '2021-05-26T15:56:00.000Z', 'symbol': 'XRP/USDT', 'timeframe': '1m', 'close': 0.9841, 'kdjk3': 22.387115436848994, 'kdjd3': 29.06774837170287, 'kdjk': 25.927200950568974, 'kdjd': 35.66617842803694, 'macd': -0.0003676537102420552, 'kdjk7': 21.758414812009285, 'kdjd7': 33.91099547763397, 'kdjk14': 25.890532277427518, 'kdjd14': 35.96124266162241, 'side': 'sell', 'confidence': 'risky', 'momentum': -9.73897747746797, 'trend': 'bearish', 'ta_ema9': 0.9858063848194416, 'ta_ema50': 0.9875401531716997, 'ta_ema200': 0.997863362716956, 'ta_atr14': 0.003707142857142861, 'atr14': 0.003619964757760064, 'min14': 0.9827, 'max14': 0.9927}
baseCurrBal: 556.21882609 percent: .4 ticker['last']: 0.9839
returning {'datetime': '2021-05-26T15:56:00.000Z', 'symbol': 'XRP/USDT', 'timeframe': '1m', 'close': 0.9843, 'kdjk3': 23.974417024150412, 'kdjd3': 29.596848900803344, 'kdjk': 26.46053428390225, 'kdjd': 35.8439562058147, 'macd': -0.0003516992942875774, 'kdjk7': 22.338124956936753, 'kdjd7': 34.10423219260979, 'kdjk14': 26.423865610760792, 'kdjd14': 36.13902043940016, 'side': 'sell', 'confidence': 'risky', 'momentum': -9.38342192191245, 'trend': 'bearish', 'ta_ema9': 0.9858463848194414, 'ta_ema50': 0.9875479963089707, 'ta_ema200': 0.9978653662659518, 'ta_atr14': 0.003721428571428574, 'atr14': 0.003634250472045777, 'min14': 0.9827, 'max14': 0.9927}
returning {'datetime': '2021-05-26T15:56:00.000Z', 'symbol': 'XRP/USDT', 'timeframe': '1m', 'close': 0.9848, 'kdjk3': 27.94267099240484, 'kdjd3': 30.91960022355482, 'kdjk': 27.79386761723572, 'kdjd': 36.28840065025919, 'macd': -0.0003118132544015495, 'kdjk7': 23.787400319255745, 'kdjd7': 34.587323980049455, 'kdjk14': 27.757198944094263, 'kdjd14': 36.583464883844655, 'side': 'sell', 'confidence': 'risky', 'momentum': -8.494533033023473, 'trend': 'bearish', 'ta_ema9': 0.9859463848194416, 'ta_ema50': 0.9875676041521483, 'ta_ema200': 0.997870375138441, 'ta_atr14': 0.0038000000000000095, 'atr14': 0.0037128219006172126, 'min14': 0.9827, 'max14': 0.9927}
baseCurrBal: 556.21882609 percent: .4 ticker['last']: 0.9842
when i compare all the kdj* values, i can not see a strong resemblance to the values over the same time period from trading view's standard stoch rsi with 3/3/14/14/close params. I have adjusted the KDJ_WINDOW and KDJ_PARAM values numerous times with just about every combination of 3, 7 and 14 that make sense to me; i've tried with calls to _calc_kd and without, i've tried adjusting KDJ_WINDODW and KDJ_PARAM in between _calc_kd calls; i've tried to only reference ['kdjk'] and ['kdjd']; i've tried use the ['kdjk_N'] columns as mentoined at https://www.programmersought.com/article/69583827158/ but i have not been able closely replicate the trading view values...
What am i missing / doing incorrectly?
(note1: that any reference to an exchange is for ccxt exchange object).
(note2: i'm using stockstats )

i ended up using the following manual calculation:
i ended up using the following manual calculation:
stock_data['rsi1'] = stock_data['rsi_14']
stock_data['rsi_L14'] = stock_data['rsi1'].rolling(window=14).min()
stock_data['rsi_H14'] = stock_data['rsi1'].rolling(window=14).max()
stock_data['stoch'] = 100*((stock_data['rsi1'] - stock_data['rsi_L14']) / (stock_data['rsi_H14'] - stock_data['rsi_L14']) )
stock_data['my_k2'] = stock_data['stoch'].rolling(window=3).mean()
stock_data['my_d2'] = stock_data['my_k2'].rolling(window=3).mean()
r['kdjk'] = stock_data['my_k2'][499]
r['kdjd'] = stock_data['my_d2'][499]
i found this pine script and used explanations at the tradingview explanation and explanation from this page to come up with the true algorithm.
i subsequently cross referenced against a live 1m chart of xrp/usdt on trading view and the values aligned almost exactly.

Related

How to write this piece of code in function?

I am using the "Divergence Indicator" script written by Tradingview with Macd, stoch and rsi at the same time.
I use the code below duplicate 3 times (for Macd, stoch and rsi)
plFound = na(ta.pivotlow(rsi, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(rsi, lbL, lbR)) ? false : true
// Regular Bullish
oscHL = rsi[lbR] > ta.valuewhen(plFound, rsi[lbR], 1) and _inRange(plFound[1])
priceLL = close[lbR] < ta.valuewhen(plFound, close[lbR], 1)
bullCond = priceLL and oscHL and plFound
// Regular Bearish
oscLH = rsi[lbR] < ta.valuewhen(phFound, rsi[lbR], 1) and _inRange(phFound[1])
priceHH = close[lbR] > ta.valuewhen(phFound, close[lbR], 1)
bear = priceHH and oscLH and phFound
Is it possible to use a function to avoid duplicating the same code 3 times?
Very simple
f_divergences(_src) =>
plFound = na(ta.pivotlow(_src, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(_src, lbL, lbR)) ? false : true
// Regular Bullish
oscHL = _src[lbR] > ta.valuewhen(plFound, _src[lbR], 1) and _inRange(plFound[1])
priceLL = close[lbR] < ta.valuewhen(plFound, close[lbR], 1)
bullCond = priceLL and oscHL and plFound
// Regular Bearish
oscLH = _src[lbR] < ta.valuewhen(phFound, _src[lbR], 1) and
_inRange(phFound[1])
priceHH = close[lbR] > ta.valuewhen(phFound, close[lbR], 1)
bear = priceHH and oscLH and phFound
[bullCond, bear]
// Calling the function three times
[rsi_bull, rsi_bear] = f_divergences(rsi)
[stoch_bull, stoch_bear] = f_divergences(stoch)
[macd_bull, macd_bear] = f_divergences(macd)

Pyspark AssertionError: on should be Column or list of Column

Hi I have the below dataframes and when I join them I get AssertionError: on should be Column or list of Column. How do I get around this please as I cannot find any solution on google related to this?
Pages = sc.read.json("/Users/me/desktop/clickstream/Clicks/Page*.json.gz")
Pages_Dataset = Pages.select("SessionNumber", "PageLocation", "PageInstanceID")\
.withColumnRenamed("PageLocation", "URL")\
.withColumnRenamed("PageInstanceID", "CsaNumber")\
.withColumn("URL2", expr("CASE WHEN INSTR(URL, '=') > 0 THEN SUBSTR(URL,0,INSTR(URL, '=') -1) ELSE URL END"))\
.withColumn("URL2", expr("CASE WHEN INSTR(URL2, '?') > 0 THEN SUBSTR(URL2,0,INSTR(URL2, '?') -1) ELSE URL2 END"))\
.withColumn("URL2", expr("CASE WHEN INSTR(URL2, '#') > 0 THEN SUBSTR(URL2,0,INSTR(URL2, '#') -1) ELSE URL2 END"))\
.withColumn("URL3", expr("CASE WHEN INSTR(URL, 'prdcls=') > 0 THEN SUBSTR(URL,INSTR(URL, 'prdcls=')+7,2) ELSE '' END"))\
.withColumn("URL", concat("URL2", "URL3"))\
.select("SessionNumber", "URL", "CsaNumber").alias("a")\
.join(ConfiguredUrls.alias("b"), lower("a.URL") == lower("b.URL"), "left")\
.select("a.SessionNumber", "b.Product", "a.CsaNumber", "b.EndQuote", "a.URL")\
.withColumnRenamed("Product", "Session")\
.withColumn("Session", expr("CASE WHEN lower(URL) like 'https://mobilephones.com/deals/%' THEN 'Mobile Phones' ELSE Session END"))\
.withColumn("EndQuote", expr("CASE WHEN lower(URL) like 'https://mobilephones.com/deals/%' THEN 'Mobile Phones' ELSE EndQuote END"))\
.distinct()
Goals_Dataset = Goals.select("SessionNumber", "GoalName", "PageInstanceID", "EventTimestamp")\
.withColumnRenamed("EventTimestamp", "GoalDate")\
.withColumnRenamed("PageInstanceID", "CsaNumber")\
.select("SessionNumber", "GoalName", "CsaNumber", "GoalDate").alias("a")\
.join(ConfiguredGoals.alias("b"), lower("a.GoalName") == lower("b.GoalNameValue"), "left")\
.select("a.SessionNumber", coalesce("b.StartQuote", "b.EndQuote", "b.Switch").alias("Session"), "a.CsaNumber", "b.EndQuote")\
.distinct()
Session_Dataset = Pages_Dataset.select("SessionNumber", "Session", "CsaNumber", "EndQuote").alias("a")\
.join(Goals_Dataset.alias("b"), "a.SessionNumber" == "b.SessionNumber", "fullouter")\
.select(coalesce("a.SessionNumber", "b.SessionNumber").alias("SessionNumber"), coalesce("a.Session", "b.Session").alias("Session"), coalesce("a.CsaNumber", "b.CsaNumber").alias("CsaNumber"), coalesce("a.EndQuote", "b.EndQuote").alias("EndQuote"))\
.distinct()
#Error:
Session_Dataset = Pages_Dataset.select("SessionNumber", "Session", "CsaNumber", "EndQuote").alias("a")\
File "/usr/local/Cellar/apache-spark/3.2.1/libexec/python/lib/pyspark.zip/pyspark/sql/dataframe.py", line 1343, in join
AssertionError: on should be Column or list of Column
"a.SessionNumber" == "b.SessionNumber" should be col("a.SessionNumber") == col("b.SessionNumber"), or just "SessionNumber"

for each group by date in coffeescript

which pulls data from and reformats it.
Promise = require "bluebird"
request = Promise.promisify require "request"
moment = require "moment"
cdn = require('config').server.cloudFrontDomain
toTitleCase = require "titlecase"
exports.getStocks = (path) ->
return new Promise (resolve, reject) ->
request path
.then (body) ->
germanStock = []
germanStocks = JSON.parse body.body
germanStocks.forEach (stock) ->
obj = {}
this.parsePart = (remaining) ->
value = remaining.value
dashIndex = value.lastIndexOf '-'
if dashIndex != -1
remaining.value = value.substring 0, dashIndex - 1
return value.substring(dashIndex + 1).trim()
else
return ''
remaining =
value: stock.name
size = parsePart remaining
colour = parsePart remaining
name = remaining.value
sku = stock.sku
styleId = sku.split(/-/)[0]
colorcode = /^(.*)-(.*)([0-9])$/.exec(sku)?[2]
bgStyle = "url(//#{cdn}/assets/product_shots/thumbs/#{styleId}-#{colorcode}.jpg)"
obj.id = sku
obj.name = name
obj.colorUrl = bgStyle
obj.colour = toTitleCase(colour.toLowerCase())
obj.size = size
obj.stock = stock.stock
obj.inProduction = ''
obj.office = 'DE'
stock.preorders.forEach (i, idx) ->
date = moment(i.date).format('DD-MM-YYYY')
if idx != stock.preorders.length - 1
obj.inProduction = obj.inProduction.concat i.amount + ' due on ' + date + ', '
else
obj.inProduction = obj.inProduction.concat i.amount + ' due on ' + date
germanStock.push obj
resolve germanStock
.catch (err) ->
reject err
where my data is like:
{
"id":1,
"stamp":"2014-09-25T12:55:30Z",
"name":" MENS T-SHIRT - BRIGHT BLUE - XS",
"sku":"SS01-BB0",
"stock":81,
"active":true,
"preorders":[
{
"id":92549,
"amount":160,
"date":"2016-06-19T22:00:00Z"
},
{
"id":92549,
"amount":200,
"date":"2016-06-19T22:00:00Z"
},
{
"id":92549,
"amount":1000,
"date":"2016-06-21T22:00:00Z"
}
],
"discountMatrix":0.0,
"stockNormalized":81,
"preOrdersSum":1360
},
{
"id":2,
"stamp":"2014-09-25T12:55:30Z",
"name":" MENS T-SHIRT - BRIGHT BLUE - S",
"sku":"SS01-BB1",
"stock":339,
"active":true,
"preorders":[
{
"id":92551,
"amount":240,
"date":"2016-06-19T22:00:00Z"
},
{
"id":92438,
"amount":160,
"date":"22016-06-19T22:00:00Z"
}
],
"discountMatrix":0.0,
"stockNormalized":339,
"preOrdersSum":400
},
what is the correct way to group each preorders quantity that is on the same date, so that instead of getting:
160 due on 19-06-2016, 200 due on 19-06-2016, 1000 due on 21-06-2016
i get 360 due on 19-06-2016, 1000 due on 21-06-2016
any advice much appreciated.
You could just use an object with the date as key and the total amount for the date as value.
For each preorder, add it's amount at it's date index in this object. At the end of the iteration print the content of the object:
moment = require "moment"
data = [
{
id:1
stamp: "2014-09-25T12:55:30Z"
name: " MENS T-SHIRT - BRIGHT BLUE - XS"
sku: "SS01-BB0"
stock:81
active:true
preorders:[
{
id:92549
amount:160
date: "2016-06-19T22:00:00Z"
}
{
id:92549
amount:200
date: "2016-06-19T22:00:00Z"
}
{
id:92549
amount:1000
date: "2016-06-21T22:00:00Z"
}
]
discountMatrix:0.0
stockNormalized:81
preOrdersSum:1360
}
]
obj = {}
obj.inProduction = ""
amountByDate = {}
# for each document in your data
for doc in data
# for each preorder in your document
for preorder in doc.preorders
# add it's amount in the index equals to it's date
if amountByDate[preorder.date]
amountByDate[preorder.date] += preorder.amount
else
# or create the index with the value if it doesn't exist
amountByDate[preorder.date] = preorder.amount
for date, amount of amountByDate
if obj.inProduction != ""
obj.inProduction = obj.inProduction.concat ", #{amount} due on #{moment(date).format('DD-MM-YYYY')}"
else
obj.inProduction = obj.inProduction.concat "#{amount} due on #{moment(date).format('DD-MM-YYYY')}"
console.log obj.inProduction
Result:
360 due on 20-06-2016, 1000 due on 22-06-2016

NameError: global name 'Carnage' is not defined

I know it was asked a million times before, but I need a little help getting this working, as the code is not mine.
so like that i update a code hope it will make some undarstands of it
# coding=utf-8
import urllib, re, sys, threading, cookielib, urllib2
from BeautifulSoup import BeautifulSoup
### Головная функция
def main():
agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)'
aCarnage = Carnage('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
aCarnage.login()
me = aCarnage.inf(aCarnage.user)
# Если ранен - выйти
if me['inj']:
aCarnage.logout()
exit(1)
aCarnage.urlopen('main.pl')
# Подождать пока здоровье восстановится
while(me['hp_wait']):
time.sleep(me['hp_wait'])
me = aCarnage.inf(aCarnage.user)
# Найти подходящую заявку
aCarnage.find()
me = aCarnage.inf(aCarnage.user)
# Если заявка состоялась - в бой!
if me['battle']: aCarnage.fight()
# После боя - выход из игры
aCarnage.logout()
class Opener:
def __init__(self, host, encoding, agent):
self.host = host
self.encoding = encoding
self.agent = agent
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
def urlopen(self, goto, data = None):
f = self.opener.open(urllib2.Request(
"http://%s/%s" % (self.host, goto),
self.urlencode(data),
{"User-agent" : self.agent}
))
result = f.read()
self.soup = BeautifulSoup(result)
def urlencode(self, data):
if data is None: return None
for key in data:
data[key] = data[key].encode(self.encoding, 'ignore')
return urllib.urlencode(data)
class CarnageBot(Opener):
### Конструктор принимает логин, пароль, кодировку (cp1251) и идентификатор браузера
def __init__(self, user, password, host, encoding, agent):
self.user = user
self.password = password
Opener.__init__(self, host, encoding, agent)
### Получить информацию об игроке - например о самом себе
def inf(self, user):
self.urlopen('inf.pl?' + self.urlencode({'user': user}))
# Кол-во жизни
onmouseover = self.soup.find('img', onmouseover = re.compile(unicode('Уровень жизни:', 'utf8')))
m = re.search('([0-9]+).([0-9]+)', onmouseover['onmouseover'])
hp = int(m.group(1))
hp_max = int(m.group(2))
hp_wait = (100 - (hp * 100) / hp_max) * 18
# Уровень
td = self.soup.find('td', text = re.compile(unicode('Уровень:', 'utf8')))
level = int(td.next.string)
# Ранен или нет
inj = 0
if self.soup.find(src = re.compile(unicode('travma.gif', 'utf8'))): inj = 1
# В бою или нет
battle = 0
if self.soup.find(text = re.compile(unicode('Персонаж находится в бою', 'utf8'))): battle = 1
hero = {'level': level, 'hp': hp, 'hp_max': hp_max, 'hp_wait': hp_wait, 'inj': inj, 'battle': battle}
return hero
### Войти в игру
def login(self):
data = {'action': 'enter', 'user_carnage': self.user, 'pass_carnage': self.password}
self.urlopen('enter.pl', data)
self.urlopen('main.pl')
### Выйти из игры
def logout(self):
self.urlopen('main.pl?action=exit')
### В бой!!!
def fight(self):
self.urlopen('battle.pl')
while True:
# Добить по таймауту
if self.soup.find(text = re.compile(unicode('Противник потерял сознание', 'utf8'))):
self.urlopen('battle.pl?cmd=timeout&status=win')
break
if self.soup.find(text = re.compile(unicode('Бой закончен.', 'utf8'))):
break
reg = re.compile(unicode('Для вас бой закончен. Ждите окончания боя.', 'utf8'))
if self.soup.find(text = reg):
break
cmd = self.soup.find('input', {'name' : 'cmd', 'type' : 'hidden'})
to = self.soup.find('input', {'name' : 'to', 'type' : 'hidden'})
# Есть ли по кому бить?!
if cmd and to:
a = random.randint(1, 4)
b0 = random.randint(1, 4)
b1 = random.randint(1, 4)
while b1 == b0: b1 = random.randint(1, 4)
pos = 2
arg = (cmd['value'], to['value'], pos, a, a, b0, b0, b1, b1)
self.urlopen('battle.pl?cmd=%s&to=%s&pos=%s&A%s=%s&D%s=%s&D%s=%s' % arg)
else:
self.urlopen('battle.pl')
time.sleep(random.randint(5, 30))
### Найти заявку - подающий заявку должен быть на 1 уровень ниже нашего
def find(self):
me = self.inf(self.user)
while True:
v = ''
self.urlopen('zayavka.pl?cmd=haot.show')
reg = re.compile(unicode('Текущие заявки на бой', 'utf8'))
script = self.soup.find('fieldset', text = reg).findNext('script')
m = re.findall('.*', script.string)
for value in m:
if value.find('group.gif') < 0: continue
if value.find('(%i-%i)' % (me['level'] - 2, me['level'])) < 0: continue
t = re.search(',([0-9]{1,2}),u', value)
if not t: continue
t = int(t.group(1))
v = re.search('tr\(([0-9]+)', value).group(1)
print 'Found battle t=%i v=%s' % (t, v)
break
if v: break
time.sleep(80)
nd = self.soup.find('input', {'name' : 'nd', 'type' : 'hidden'})
self.urlopen('zayavka.pl?cmd=haot.accept&nd=%s&battle_id=%s' % (nd['value'], v))
time.sleep(t + 30)
if __name__ == '__main__': main()
The error is:
NameError: global name 'Carnage' is not defined
The cause of your error is that Carnage has not been defined. Maybe you forgot to import a library which provides Carnage?
Also, your code as posted is incorrectly indented, which is a syntax error.
Update: Apparently you took this code from http://github.com/Ejz/Common/tree/master/carnage-bot . Reading that source, it looks like the line
aCarnage = Carnage('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
Should be
aCarnage = CarnageBot('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
Because the methods called on aCarnage are defined further down the file for class CarnageBot.

Class Methods not linking to Tkinter GUI

it seems my Tkinter GUI is fine however when loaded the buttons which should activate the class methods do nadda.
I was originally trying to initiate a class instance within the main:
if_name_== "main":
ed.EditorUI()
Where 'self' is used below 'ed' was in its place.. it said ed was undefined which prompted me to try this way.
As you can probably tell its been a few years since I've coded.
Your help is much appreciated!
import CU_picture
import filters
import Tkinter
root = Tk()
root.title('Photo Editor Version 1.10')
#root.iconbitmap(bitmap = '12.ico')
#img = PhotoImage(file='12.ico')
#root.tk.call('wm', 'iconphoto', root._w, img)
#Adding File Menu
menubar = Tkinter.Menu(root)
filemenu = Tkinter.Menu(menubar, tearoff=0)
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
#Display above menus
root.config(menu=menubar)
class EditorUI(object):
def __init__(self):
self.name = "EditorUI"
self.pic = 0
self.pix = CU_picture.Picture()
self.filters = "No Current Filters Applied"
self.special = "cake"
def get_specific_color(color):
if color == "red":
return CU_picture.Color(255, 0, 0)
elif color == "aqua":
return CU_picture.Color(0, 255, 255)
elif color == "fuschia":
return CU_picture.Color(255, 0, 255)
elif color == "lime":
return CU_picture.Color(0, 255, 0)
elif color == "yellow":
return CU_picture.Color(255, 255, 0)
def load():
self.pix = get_picture()
self.pix.show()
self.pic = 1
error.set("Pic Loaded: "+self.filters)
outtext.set("New Picture - Not Saved.")
self.filters = "No Current Filters Applied"
self.special = "cake"
para.set("")
def save():
if self.pic == 0:
error.set("No Pic Loaded")
else:
name = intext.get() + ".jpg"
self.pix.write_to(name)
outtext.set("Saved To Given Filename.")
para.set("")
def negative():
if self.pic == 0:
error.set("No Pic Loaded")
else:
n = filters.NegativeFilter()
n.apply(ed.pix)
self.pix.show()
para.set("")
if self.filters == "No Current Filters Applied":
self.filters = "Negative-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Negative-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def grayscale():
if self.pic == 0:
error.set("No Pic Loaded")
else:
g = filters.GrayScaleFilter()
g.apply(self.pix)
self.pix.show()
para.set("")
if self.filters == "No Current Filters Applied":
self.filters = "Grayscale-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Grayscale-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def posterize():
if self.pic == 0:
error.set("No Pic Loaded")
else:
p = filters.PosterizeFilter()
p.apply(self.pix)
self.pix.show()
para.set("")
if self.filters == "No Current Filters Applied":
self.filters = "Posterize-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Posterize-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def highlight():
if self.pic == 0:
error.set("No Pic Loaded")
else:
if intext.get() == "":
para.set("Input Highlight distance/Colour and try again(one at a time).")
elif self.special == "cake" and intext.get() != "":
self.special = intext.get()
outtext.set("Highlight distance: " + self.special)
para.set("Input Highlight colour(red, blue, aqua, fuschia, lime, yellow) for the final step.")
elif self.special != "cake" and intext.get() != "":
color = get_specific_color(intext.get())
h = filters.HighlightFilter()
h.set_distance(float(self.special))
h.set_color(color)
outtext.set("Highlight colour: " + intext.get())
h.apply(self.pix)
self.pix.show()
if self.filters == "No Current Filters Applied":
self.filters = "Highlight-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Highlight-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def edge():
if self.pic == 0:
error.set("No Pic Loaded")
else:
para.set("Threshold?")
if intext.get() == "":
para.set("Input Threshold value and try again.")
else:
para.set("Threshold: " + intext.get())
e = filters.EdgeFilter()
e.set_threshold(float(intext.get()))
e.apply(self.pix)
self.pix.show()
if self.filters == "No Current Filters Applied":
self.filters = "Edge-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Edge-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def get_picture():
"""
Interactively select a picture file and return it.
"""
# Pop up a dialogue box to select a file
file = CU_picture.pick_a_file()
# Open the file containing the picture and load it
pict = CU_picture.load_picture(file)
return pict
if __name__ == "__main__":
EditorUI()
intext = Tkinter.StringVar()
outtext = Tkinter.StringVar()
error = Tkinter.StringVar()
para = Tkinter.StringVar()
inp = Tkinter.Entry(root, textvariable=intext)
out = Tkinter.Label(root, textvariable=outtext)
ER = Tkinter.Label(root, textvariable=error)
P = Tkinter.Label(root, textvariable=para)
load = Tkinter.Button(root, text="Load", height=2, width=20, command=load)
save = Tkinter.Button(root, text="Save", height=2, width=20, command=save)
negative = Tkinter.Button(root, text="Negative-F", height=1, width=20, command=negative)
grayscale = Tkinter.Button(root, text="Grayscale-F", height=1, width=20, command=grayscale)
posterize = Tkinter.Button(root, text="Posterize-F", height=1, width=20, command=posterize)
highlight = Tkinter.Button(root, text="Highlight-F", height=1, width=20, command=highlight)
edge = Tkinter.Button(root, text="Edge-F", height=1, width=20, command=edge)
inp.grid(row=1, column=7)
ER.grid(row=0, column= 0, columnspan=5, rowspan=2)
out.grid(row=1, column= 0, columnspan=5, rowspan=2)
P.grid(row=2, column= 0, columnspan=5, rowspan=2)
load.grid(row=0, column=6)
save.grid(row=0, column=7)
negative.grid(row=1, column=6)
grayscale.grid(row=3, column=7)
posterize.grid(row=3, column=6)
highlight.grid(row=2, column=6)
edge.grid(row=2, column=7)
root.mainloop()
One of the main problems that I see (other than what #A.Rodas mentioned above) that would prevent the buttons from doing anything is that your button commands are not actually targeting the class methods. They're looking for root-level callables named "load", "save", etc. Because these don't exist, you should be getting errors, and yet you say the interface works fine aside from the buttons not cooperating, which doesn't make sense to me.
To call the class methods, you must create an instance of the class. First fix the self issue mentioned by #A.Rodas above, then replace the __main__ check with this:
editor = EditorUI()
Then modify the button commands to call the methods on the editor instance:
load = Tkinter.Button(root, text="Load", height=2, width=20, command=editor.load)
save = Tkinter.Button(root, text="Save", height=2, width=20, command=editor.save)
negative = Tkinter.Button(root, text="Negative-F", height=1, width=20, command=editor.negative)
grayscale = Tkinter.Button(root, text="Grayscale-F", height=1, width=20, command=editor.grayscale)
posterize = Tkinter.Button(root, text="Posterize-F", height=1, width=20, command=editor.posterize)
highlight = Tkinter.Button(root, text="Highlight-F", height=1, width=20, command=editor.highlight)
edge = Tkinter.Button(root, text="Edge-F", height=1, width=20, command=editor.edge)
You may also consider moving all the interface creation stuff inside the EditorUI class, unless you have some other reason for keeping it separate.