class Rule(): def __init__(self, market, period): self.market = market self.period = period self.KLines = KLine() self.MACD = MACD() self.KDJ = KDJ() self.WaveKline = WaveKline() self.WaveMACD_DIFF = WavePoint() self.WaveMACD_DEA = WavePoint() self.WaveMACD_MACD = WavePoint() self.WaveKDJ_K = WavePoint() self.WaveKDJ_D = WavePoint() # self.client = Client(access_key=RebotConfig.access_key, secret_key=RebotConfig.secret_key) self.begin = 0 def Run(self, d): # d = self.client.get(get_api_path('k'), params={'market': '{0}cny'.format(self.market), 'limit':100,'period' : '{0}'.format(self.period)}); # print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(d[0][0])); self.KLines.Input(d) self.MACD.Input(self.KLines) self.KDJ.Input(self.KLines) self.WaveKline.Input(self.KLines) self.WaveMACD_DIFF.Input(self.MACD.DIFF) self.WaveMACD_DEA.Input(self.MACD.DEA) self.WaveKDJ_K.Input(self.KDJ.K) self.WaveKDJ_D.Input(self.KDJ.D) klen = len(self.KLines) self.begin = klen # self.WaveKline.Export("C:\\Users\\randy\\k.csv"); # macd diff, dea 0 de daxiao def Trend(self): lmacd = len(self.MACD) if lmacd < 2: return Direction.FLAT if self.MACD.DIFF[lmacd - 1] >= 0 and self.MACD.DIFF[ lmacd - 2] >= 0 and self.MACD.DEA[ lmacd - 1] >= 0 and self.MACD.DEA[lmacd - 2] >= 0: return Direction.UP return Direction.DOWN def Do(self): d = self.Trend() kc = self.WaveKline.Get(-1) kp = self.WaveKline.Get(-2, kc.dir) k = self.KLines.Get(-1) klen = len(self.KLines) if kc.hkidx < 0 or kc.lkidx < 0 or kp == None: return None # print 'kc:',kc,'kp:',kp # print kp.hk.c, kc.hk.c, kp.lk.c, kp.lk.c if kp.hk.h <= kc.hk.h and kp.hk.c > kc.lk.c: # # print "\n" # print kp.hk.c, kc.hk.c, kc.lk.c # print 'kc:',kc,'kp:',kp ktrend = self.WaveKline.TrendWeaken() macdtrend = self.WaveMACD_DIFF.TrendWeaken(kc.dir) kdjkseg = self.WaveKDJ_K.Get(-1) #if ktrend: # print "sell", klen-1, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t)), d, ktrend, macdtrend, kdjkseg.dir # sell if ktrend and macdtrend and kdjkseg.dir == Direction.DOWN: return 'sell' if kp.lk.c > kc.lk.c and kp.lk.c < kc.hk.c: # ktrend = self.WaveKline.TrendWeaken() macdtrend = self.WaveMACD_DIFF.TrendWeaken(kc.dir) kdjkseg = self.WaveKDJ_K.Get(-1) #if ktrend: # print "buy", klen-1, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t)), ktrend, macdtrend, kdjkseg.dir # buy if ktrend and macdtrend and kdjkseg.dir == Direction.UP: return 'buy' return None
class WVStats(): def __init__(self, ValueN=10): self.KLines = KLine() self.Value = [] self.Volume = [] self.ValueN = ValueN self.status = None self.statuscost = 0 self.statusbuycurrent = 0 self.statusdelay = 0 self.stats = [] self.High = [] self.Low = [] self.lastidx = 0 self.lastbuyidx = 0 def Export(self, path): f = open(path, 'wb') w = csv.writer(f) w.writerow([ 'increase', 'amplitude', 'close', 'vol', 'value', 'volume', 'increase', 'amplitude', 'close', 'vol', 'value', 'volume', 'increase', 'amplitude', 'close', 'vol', 'value', 'volume', 'increase', 'amplitude', 'close', 'vol', 'value', 'volume', 'increase', 'amplitude', 'close', 'vol', 'value', 'volume' ]) for k, arr in enumerate(self.stats): d = [] for i in range(0, len(arr)): nd = arr[i] d.append(nd['k'].increase) d.append(nd['k'].amplitude) d.append(nd['k'].c) d.append(nd['k'].vol) d.append(nd['value']) d.append(nd['volume']) w.writerow(d) f.close() return def Run(self, d, period=None, servertimestamp=None): if len(d) == 0: return self.lastidx = self.KLines.Input(d) MA(self.KLines.prices, self.Value, self.ValueN) MA(self.KLines.volumes, self.Volume, self.ValueN) HIGH(self.KLines.prices, self.High, self.ValueN * 2) LOW(self.KLines.prices, self.Low, self.ValueN * 2) if len(self.KLines) > self.ValueN + 1: return self.Do() return { 'type': None } def Do(self, idx=-1, ignore=False): summ, ccount = self.KLines.Sum(12) summb = round(summ / 5000000, 2) avgp = self.KLines.Ref(12, 'c', -2) prek = self.KLines.Get(idx - 1) prevolume = self.Volume[idx - 1] prevalue = self.Value[idx - 1] k = self.KLines.Get(idx) value = self.Value[idx] volume = self.Volume[idx] phigh = self.High[-2] plow = self.Low[-2] ret = {} ret['type'] = None ret['k'] = k ret['sort'] = 1 ret['angle'] = 10 ret['ext'] = {'summ': summb} statslen = len(self.stats) for i in range(0, statslen): nk = statslen - i - 1 arr = self.stats[nk] if len(arr) < 5: arr.append({ 'k': k, 'value': value, 'volume': volume }) self.stats.append([]) dv = 1 avgpp = 0 if avgp > 0: avgpp = round((k.c - avgp) / avgp * 100, 2) else: print '\t\tavgp is eq 0', avgp # print "xxxx", self.lastidx, self.statusbuycurrent, self.statusdelay, self.status; if self.status == 'buy': bk = self.KLines.Get(self.lastbuyidx) dv = (self.statuscost - self.statusbuycurrent) / self.statuscost * 2 + 1 dv = round(dv, 2) scale = (self.statuscost - k.c) / self.statuscost > MAXBETA * dv delay = (self.lastidx - self.statusdelay) > MAXKCOUNT * dv # print (self.statuscost - k.c)/self.statuscost, MAXBETA * dv, dv, self.statusdelay, MAXKCOUNT * dv, prek.c > prevalue, prek.vol / (VOLTIMES * prevolume); avgscale = (k.c - self.statusbuycurrent) / self.statuscost * 100 avgscale = round(avgscale, 2) # delayw = avgpp < 0 or avgpp > 5 * summ / 5000000; delayw = False #avgpp < 0 ;# or avgscale < 5*summ/5000000; if bk.increase * 100 > 15 * dv: delayw = True print 'buy k increase'.bk.increase if scale or delayw or delay or avgscale < -7: ret['type'] = 'sell' ret['ext']['dv'] = dv ret['ext']['scale'] = scale ret['ext']['avgscale'] = avgscale ret['ext']['delay'] = delay ret['ext']['avgpp'] = avgpp return ret if self.statuscost < k.c: self.statuscost = k.c #if prek.vol > VOLTIMES * prevolume: # print prek.c, prevalue, prek.c > prevalue, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(prek.t)); # if (prek.c > prevalue and prek.vol > VOLTIMES * prevolume * dv) or (k.c > value and k.vol > VOLTIMES * volume * dv): #and k.c > phigh :#and k.vol < 3.5 * volume: closev = round((k.c - value) / value * 100, 2) if self.lastbuyidx != self.lastidx - 1 and summb >= 1 and closev > 1 and closev <= 10 and avgpp / closev > 0.5 and avgpp <= 10 and k.vol > VOLTIMES * volume * dv and self.statusdelay != self.lastidx: #and k.c > phigh :#and k.vol < 3.5 * volume: # if (k.c > value and k.vol > VOLTIMES * volume * dv and k.vol < 8 * VOLTIMES * volume * dv ) and self.statusdelay != self.lastidx: #and k.c > phigh :#and k.vol < 3.5 * volume: ret['type'] = 'buy' self.status = 'buy' ret['ext']['close'] = closev ret['ext']['voltimes'] = round(k.vol / volume, 2) ret['ext']['avgpp'] = avgpp ret['ext']['ss'] = round(avgpp / closev, 2) if self.statusbuycurrent == 0: self.statuscost = k.c self.statusbuycurrent = k.c self.statusdelay = self.lastidx else: self.statusdelay = self.lastidx + (self.lastidx - self.statusdelay) / 3 self.lastbuyidx = self.lastidx - 1 return ret return ret def OrderResult(self, ret, orderresult): Log.d( '\t\torder result, self status {0}, result type {1}, order result {2}' .format(self.status, ret['type'], orderresult)) if ret['type'] == 'sell': if orderresult: self.status = 'sell' self.statuscost = 0 self.statusdelay = 0 self.statusbuycurrent = 0
class WVStats(): def __init__(self, ValueN=10): self.KLines = KLine() self.Value = [] self.Volume = [] self.ValueN = ValueN self.status = None self.statuscost = 0 self.statusbuycurrent = 0 self.statusdelay = 0 self.stats = [] self.High = [] self.Low = [] self.lastidx = 0 def Export(self, path): f = open(path, 'wb') w = csv.writer(f) w.writerow([ 'increase', 'amplitude', 'close', 'vol', 'value', 'volume', 'increase', 'amplitude', 'close', 'vol', 'value', 'volume', 'increase', 'amplitude', 'close', 'vol', 'value', 'volume', 'increase', 'amplitude', 'close', 'vol', 'value', 'volume', 'increase', 'amplitude', 'close', 'vol', 'value', 'volume' ]) for k, arr in enumerate(self.stats): d = [] for i in range(0, len(arr)): nd = arr[i] d.append(nd['k'].increase) d.append(nd['k'].amplitude) d.append(nd['k'].c) d.append(nd['k'].vol) d.append(nd['value']) d.append(nd['volume']) w.writerow(d) f.close() return def Run(self, d, period=None, servertimestamp=None): if len(d) == 0: return self.lastidx = self.KLines.Input(d) MA(self.KLines.prices, self.Value, self.ValueN) MA(self.KLines.volumes, self.Volume, self.ValueN) HIGH(self.KLines.prices, self.High, self.ValueN * 2) LOW(self.KLines.prices, self.Low, self.ValueN * 2) if len(self.KLines) > self.ValueN + 1: return self.Do() return { 'type': None } def Do(self, idx=-1, ignore=False): prek = self.KLines.Get(idx - 1) prevolume = self.Volume[idx - 1] prevalue = self.Value[idx - 1] k = self.KLines.Get(idx) value = self.Value[idx] volume = self.Volume[idx] phigh = self.High[-2] plow = self.Low[-2] ret = {} ret['type'] = None ret['k'] = k ret['sort'] = 1 ret['angle'] = 10 ret['ext'] = {'idx': idx} statslen = len(self.stats) for i in range(0, statslen): nk = statslen - i - 1 arr = self.stats[nk] if len(arr) < 5: arr.append({ 'k': k, 'value': value, 'volume': volume }) self.stats.append([]) dv = 1 # print "xxxx", self.lastidx, self.statusbuycurrent, self.statusdelay, self.status; if self.status == 'buy': dv = (self.statuscost - self.statusbuycurrent) / self.statuscost * 2 + 1 scale = (self.statuscost - k.c) / self.statuscost > MAXBETA * dv delay = (self.lastidx - self.statusdelay) > MAXKCOUNT * dv # print (self.statuscost - k.c)/self.statuscost, MAXBETA * dv, dv, self.statusdelay, MAXKCOUNT * dv, prek.c > prevalue, prek.vol / (VOLTIMES * prevolume); if scale or delay: ret['type'] = 'sell' ret['ext'] = { 'idx': idx, 'dv': dv, 'scale': scale, 'delay': delay, } return ret if self.statuscost < k.h: self.statuscost = k.h #if prek.vol > VOLTIMES * prevolume: # print prek.c, prevalue, prek.c > prevalue, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(prek.t)); # if (prek.c > prevalue and prek.vol > VOLTIMES * prevolume * dv) or (k.c > value and k.vol > VOLTIMES * volume * dv): #and k.c > phigh :#and k.vol < 3.5 * volume: if ( k.c > value and k.vol > VOLTIMES * volume * dv ) and self.statusdelay != self.lastidx: #and k.c > phigh :#and k.vol < 3.5 * volume: ret['type'] = 'buy' self.status = 'buy' ret['ext']['close'] = (k.c - value) / value * 100 ret['ext']['voltimes'] = k.vol / volume if self.statusbuycurrent == 0: self.statuscost = k.c self.statusbuycurrent = k.c self.statusdelay = self.lastidx else: self.statusdelay = self.lastidx + (self.lastidx - self.statusdelay) / 3 return ret return ret def OrderResult(self, ret, orderresult): Log.d( '\t\torder result, self status {0}, result type {1}, order result {2}' .format(self.status, ret['type'], orderresult)) if ret['type'] == 'sell': if orderresult: self.status = 'sell' self.statuscost = 0 self.statusdelay = 0 self.statusbuycurrent = 0
class MutliMovingAverage(): def __init__(self, N1=5, N2=10, N3=21, N4=42, N5=84): self.KLines = KLine(); # price self.MA1 = []; self.MA2 = []; self.MA3 = []; self.MA4 = []; self.MA5 = []; self.N1 = N1; self.N2 = N2; self.N3 = N3; self.N4 = N4; self.N5 = N5; self.status = None; # volume self.VMA1 = []; self.VMA2 = []; self.rmbvolumeN3 = 0; # points self.points = [[], [], []]; # wave self.waves = [[], [], []]; # trade time self.tradeSure = [{'buy':0, 'sell':0}, {'buy':0, 'sell':0}]; self.tradeidx= 0; # kdj # self.KDJ = KDJ(); # ma3 price wave point; # self.ma3rate = []; # self.wavepointm3 = WavePoint(); #self.wavewavepointm3 = WavePoint(); def Run(self, d, period=None, servertimestamp=None): if period and servertimestamp: data = d[-1]; x = servertimestamp - data[0]; if x < period: data[5] /= x; # virtual volume # k self.KLines.Input(d); # kdj # self.KDJ.Input(self.KLines); # price lena = len(self.MA1); MA(self.KLines.prices, self.MA1, self.N1); MA(self.KLines.prices, self.MA2, self.N2); MA(self.KLines.prices, self.MA3, self.N3); MA(self.KLines.prices, self.MA4, self.N4); MA(self.KLines.prices, self.MA5, self.N5); # volume MA(self.KLines.volumes, self.VMA1, self.N1); MA(self.KLines.volumes, self.VMA2, self.N2); # ma3 rate and wavepoint; # RATE(self.MA3, self.ma3rate, self.N3); # self.wavepointm3.InputTrend(self.ma3rate); # self.wavewavepointm3.InputTrend(self.wavepointm3.points); lenb = len(self.MA2); lenc = lenb - lena; if lenc >= 2: for k in range(lena, lenc - 1): self.tradeidx = k; self.tradeSure = [{'buy':0, 'sell':0}, {'buy':0, 'sell':0}]; self.Do(k, True); lastk = self.KLines.Get(-1); if lastk.idx > self.tradeidx: self.tradeSure = [{'buy':0, 'sell':0}, {'buy':0, 'sell':0}]; self.tradeidx += 1; return self.Do(); def Export(self, path): if len(self.MA1) < 1: return ; f = open(path, 'wb'); w = csv.writer(f); w.writerow(['index', 'MA1', 'MA2', 'MA3', 'MA4']); for k in range(0, len(self.MA1)): w.writerow([k, self.MA1[k], self.MA2[k], self.MA3[k], self.MA4[k]]); f.close(); def ExportWave(self, path): if len(self.waves) < 0: return; f = open(path, 'wb'); wcsv = csv.writer(f); wcsv.writerow(['index', 'type', 'point1.idx', 'point2.idx', 'wmax', 'wmin', 'wvolume', 'winterval', 'cvolume', 'cprice']); for k in range(0, len(self.waves)): w = self.waves[k]; wcsv.writerow([k, w.type, w.point1.idx, w.point2.idx, w.wmax, w.wmin, w.wvolume, w.winterval, w.cvolume, w.cprice]); f.close(); def Do(self, idx=-1, ignore=False): ret = {}; k = self.KLines.Get(idx); type=None; pwidx = 0; bc43 = CROSS(self.MA4, self.MA3, idx); if bc43: self.tradeSure[0]['sell'] += 1; print "\tma long n3 n4 sell time:{0}, c:{1}, k idx:{2}, sure time:{3}, ignore:{4}".format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t)), k.c, k.idx, self.tradeSure[0]['sell'], ignore) if ignore or self.tradeSure[0]['sell'] >= RebotConfig.rebot_trade_sure_times: self.status = 'sell'; type = 'sell'; sc34 = CROSS(self.MA3, self.MA4, idx); if sc34: self.tradeSure[0]['buy'] += 1; print "\tma long n3 n4 buy time:{0}, c:{1}, k idx:{2}, sure time:{3}, ignore:{4}".format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t)), k.c, k.idx, self.tradeSure[0]['buy'], ignore) if ignore or self.tradeSure[0]['buy'] >= RebotConfig.rebot_trade_sure_times: self.status = 'buy' type = 'buy'; if self.status == 'buy' and type == None and False: type = self.KDJ.Do(); if type: pwidx = 2; print "kdj:{0} time:{1}, c:{2}, k idx:{3}".format(type, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t)), k.c, k.idx) if type == None:# and self.status == 'buy': bc = CROSS(self.MA2, self.MA1, idx); if bc: self.tradeSure[1]['sell'] += 1; print "\tma short n1 n2 sell time:{0}, c:{1}, k idx:{2}, sure time:{3}, ignore:{4}".format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t)), k.c, k.idx, self.tradeSure[1]['sell'], ignore) if ignore or self.tradeSure[1]['sell'] >= RebotConfig.rebot_trade_sure_times: type = 'sell'; pwidx = 1; sc = CROSS(self.MA1, self.MA2, idx); if sc: self.tradeSure[1]['buy'] += 1; print "\tma short n1 n2 buy time:{0}, c:{1}, k idx:{2}, sure time:{3}, ignore:{4}".format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t)), k.c, k.idx, self.tradeSure[1]['buy'], ignore) if ignore or self.tradeSure[1]['buy'] >= RebotConfig.rebot_trade_sure_times: type = 'buy'; pwidx = 1; if type != None: # frist update points = self.points[pwidx]; waves = self.waves[pwidx]; lenwaves = len(waves); lenpoints = len(points); p1wave = None; p2wave = None; c1wave = None; c2wave = None; sort = 1000; p1 = None; p2 = None; if lenpoints > 0: p2 = points[-1]; if p2.idx != k.idx: np2 = Point(type, k.idx); if p2.type == type: points[-1] = np2; else: points.append(np2); p2 = np2; else: p2 = Point(type, k.idx); points.append(p2); lenpoints = len(points) if lenpoints >= 2: p1 = points[-2]; if p1 and p2: if lenwaves > 0: c1wave = waves[-1]; if c1wave.point2.idx == k.idx: c1wave.cal(self.KLines); if c1wave.type == type: c1wave.point2 = p2; c1wave.cal(self.KLines); else: ncwave = Wave(p1, p2); ncwave.cal(self.KLines); waves.append(ncwave); c1wave = ncwave; else: c1wave = Wave(p1, p2); c1wave.cal(self.KLines); waves.append(c1wave); if lenwaves >= 4 and pwidx == 1 and True: if self.status != 'buy' and False: type = None; else: c2wave = waves[-3]; p1wave = waves[-2]; p2wave = waves[-4]; if type == 'buy': type = None; sort = -215 if c1wave.wmin > c2wave.wmax: sort = c2wave.height/c1wave.height + c2wave.volheight/c1wave.volheight + p2wave.height/p1wave.height + p2wave.volheight/p1wave.volheight; # print c1wave # print c2wave # print 'buysort', sort, c2wave.height/c1wave.height, c2wave.volheight/c1wave.volheight, p2wave.height/p1wave.height, p2wave.volheight/p1wave.volheight, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t)); if sort < 4 :#and p2wave.height/p1wave.height <= 1: type = 'buy'; # print '\t short ma wave buy sucess'; else: print ' !!! wave buy sort %f, time:%s' % (sort, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t))); else: print ' !!! wave buy c1wave wwin less c2wave wmax'; if type == 'sell': # print '\tc1wave', c1wave # print '\tc2wave', c2wave if c1wave.cprice > c2wave.wmax: type = None; print '\t !!! wave sell fail current price greater c2wave wmax time:{0}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t))); else: print '\t short ma wave sell sucess'; if pwidx == 0 or type == 'sell': # long long sort = 1; if type == 'buy' and len(self.points[0]) >= 2: p1 = self.points[0][-1]; p2 = self.points[0][-2]; # print 'tan p1 p2', 57.2956 * math.atan( (self.MA4[p2.idx] - self.MA4[p1.idx])/self.MA4[p1.idx] * 100 /(p1.idx - p2.idx)), (self.MA4[p2.idx] - self.MA4[p1.idx])/self.MA4[p1.idx] * 100 /(p1.idx - p2.idx); # print 'tan c p1', 57.2956 * math.atan( (self.MA4[k.idx] - self.MA4[p1.idx])/self.MA4[p1.idx] * 100/(k.idx - p1.idx)), (self.MA4[k.idx] - self.MA4[p1.idx])/self.MA4[p1.idx] * 100/(k.idx - p1.idx); # sort = self.MA4[p.idx] / self.MA4[-1]; if self.MA4[-1] - self.MA4[p1.idx] < 0 and pwidx != 0: sort = -sort; if k.idx - p1.idx > 0: ret['angle'] = 57.2956 * math.atan( (self.MA4[p2.idx] - self.MA4[p1.idx])/self.MA4[p1.idx] * 100 /(p1.idx - p2.idx)) + 57.2956 * math.atan( (self.MA4[k.idx] - self.MA4[p1.idx])/self.MA4[p1.idx] * 100/(k.idx - p1.idx)) else: ret['angle'] = 57.2956 * math.atan( (self.MA4[p2.idx] - self.MA4[p1.idx])/self.MA4[p1.idx] * 100 /(p1.idx - p2.idx)); ret['angle'] = 10; sort = 1; # ma5v = self.MA5[p1.idx] - self.MA5[p2.idx]; ma5v = self.MA5[-1] - self.MA5[p2.idx] #if ma5v < 0: # sort = -214; # print '\t !!! ma5 buy less 0:{0}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(k.t))); ret['type'] = type; ret['k'] = k; ret['sort'] = sort; ret['ext'] = {'idx':pwidx} if type != None: self.tradeSure[pwidx][type] = -RebotConfig.rebot_do_per_period; return ret;