def main(): parser = argparse.ArgumentParser() parser.add_argument("action", choices=["backtest", "trade"]) args = parser.parse_args() if args.action == "backtest": backtest.backtest() if args.action == "trade": trade.trade()
def run(): stk_pairs = strategy.filter_pairs(dataFrame, sequence=FILTER_SEQ, number=n) global resDataFrame resDataFrame = trade.trade(tb, m, open_lim, loss_lim, g, U, dataFrame, values, stk_pairs, M) utils.xprint(os.linesep + 'Trade processed successfully!')
def process_cycle(monograph, graph): cycle = collect_negative_cycle(graph) if cycle != None: logs = trade(graph, monograph, cycle) logger.write(logs) #json_io.save(graph) #csv_io.save(graph) time.sleep(1) time.sleep(2)
def __init__(self): self.data_handler = datahandler_factory.data_handler_factory( ).get_data_handler() self.reporter = reporter_factory.reporter_factory().get_reporter() self.utility = utility.utility() self.trades = {} pair_list = config.PAIR_LIST.split() for pair in pair_list: self.trades[pair] = trade.trade(pair)
def initial(self): '''每天初始化设置 ''' logger.info("[INITIAL]:start initial !!!!!") logger.info("[INITIAL]:try to create connect... ") self.connect() self.trader = trade(UserID=self.userid,api=self.api,mock=False,server=self.server) logger.info("[INITIAL]:connect successful!") self.trading = self.judgetradeday() logger.info("[INITIAL]:initial finished !!!!!")
def market(numberOfAgents, numberOfGoods, utilityExponents, endownments, adj, quantum): m = numberOfAgents n = numberOfGoods agents = [] for i in range(0, m): u = walrasian.cobbDouglas(np.array([utilityExponents[i, :]])) g = goods.Goods(np.array([endownments[i, :]]), np.zeros((1, n))) a = agent.Agent(i, g, u) a.setAdj(adj) agents.append(a) net = network.Network(agents, adj) netAfterTrade = trade.trade(net, quantum, 100) return netAfterTrade
def initial(self): '''每天初始化设置 ''' logger.info("[INITIAL]:start initial !!!!") if not self.istradeday: self.trading = False return self.trading = True logger.info("[INITIAL]:try to create connect... ") self.connect() self.trader = trade(UserID=self.userid, api=self.api, mock=self.mock, server=self.server) logger.info("[INITIAL]:connect successful!") self.set_number() #设置手数 logger.info("[INITIAL]:initial finished !!!!!")
def initial(self): '''每天初始化设置 ''' logger.info("[INITIAL]:start initial !!!!!!") if not self.istradeday: self.trading = False return self.trading = True logger.info("[INITIAL]:try to create connect... ") self.connect() self.trader = trade(UserID=self.userid,api=self.api,mock=self.mock,server=self.server) logger.info("[INITIAL]:connect successful!") logger.info("[INITIAL]:initial account info...") self.updatetotal() #更新账户总资金 self.set_permoney() #设置单个品种资金上限 logger.info("[INITIAL]:set per product money limit:{}".format(self.permoney)) self.set_instrument() #设置交易股票和手数 logger.info("[INITIAL]:set stock list succcessful !!!") logger.info("[INITIAL]:initial finished!!!!!!")
def main(): cnx = mysql.connector.connect(user='******', password='******', host='192.168.0.16', database='gekkoTests') startingDate = datetime(2018, 7, 24) # startingDate.date.replace() dateDelta = 30 currencyToTrade = 'ETH' assetToTrade = 'V' candle_Size_Minutes = 15 warmup_Size_Minutes = 55 tradeExchange = 'binance' Initial_Assets = 100 Initial_Currency = 100 strat = 'McKee_EMA_RSI_Strat_Stoploss' trader = trade(startingDate, dateDelta, currencyToTrade, assetToTrade, candle_Size_Minutes, warmup_Size_Minutes, tradeExchange, Initial_Assets, Initial_Currency, strat, cnx) #trader.run(True) #trader.Initial_Assets = 100 #trader.Initial_Currency = 0 #trader.run(False) while True: trader.start_date = trader.start_date - timedelta(dateDelta) trader.asset = 'EOS' trader.run(False) trader.asset = 'ZRX' trader.run(False) trader.asset = 'TRX' trader.run(True)
TD = 4 # today H = 5 L = 6 NUM = 7 plt.rcParams['animation.ffmpeg_path'] = u'.\\ffmpeg.exe' # filen = '601318.XSHG.txt' filen = 'lL0.txt' fig = plt.figure() ax = fig.add_subplot(111) dohlc = data_ohlc(filen, True) trd = trade() plts = list(range(PLTS.NUM)) maxs = [] mins = [] csv = log_csv(filen, ['D', 'P'], False) opened = [False, False] seq = [] class V: summit_range = 15 open_percentage = 0.5 waiting_for_input = False
user.keepalive() account_flag = flag.flag() limit = zxb_limit.zxb_limit(-2.31) #添加trade if ed.is_tradetime_now(): file_name = '/home/way/signal/chicang' file_name1 = '/home/way/signal/zhenfu' # with open(file_name) as f: # yiyue = str(f.readlines()[0]) m = multiprocessing.Process(target=account_info,args=(account_flag,)) m.start() if account_flag.read_flag() == 2: chiyou_feed = feed.feed('chicang') chicang_trade = trade.trade(chiyou_feed.load(), user) print('chiyou') p=multiprocessing.Process(target=chiyou, args=(chicang_trade, limit)) p.start() elif account_flag.read_flag() in (4,8): # with open(file_name1) as f: # yiyue = str(f.readlines()[0]) # s = stockpool.Stockpool() # # eryuedata = s.load(table=yiyue, day=120) # # base_info, data = tradable() # # zhenfu = cser.zhenfu(base_info, eryuedata)
def play1(): object = trade.trade() print object.eyes print object.trade()
# coding=utf-8 from appium import webdriver from time import sleep from homepage import home from market import market from trade import trade from news import news desired_caps = { 'platformName': 'iOS', 'noReset': True, 'platformVersion': '10.3', "deviceName": "iPhone 6s Plus", "bundleId": "com.lanyilive.YXFuture", "udid": "6eaec690714d9d23c386339e0c07268109d9fabc", "automationName": "XCUITest" } driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) sleep(2) x = driver.get_window_size()['width'] y = driver.get_window_size()['height'] home(driver, x, y) market(driver) trade(driver) news(driver, x, y)
from Param import Param from model import model from predict import predict import dataHelper as dh from trade import trade # BEGIN for i in range(len(Param.filenames)): if Param.remodel: model(file_number=i) else: # Fetch data to ensure proper scalers are available train_X = dh.get_training_input(Param.filenames[i]) train_Y = dh.get_training_output(Param.filenames[i]) # END if predictions = predict(file_number=i) predictions = dh.get_column(Param.col_to_trade_on, predictions) profit = trade(predictions, file_number=i) print("Profit for model " + str(i) + ": " + str(profit)) # END for
else: btypes.append(0) scress.append(isscre) counts.append(count) amounts.append(cent.balance) stores.append(cent.store) sumAmount = float( cent.balance) + float(cent.store) * float(close_prices[i]) sumAmounts.append(sumAmount) return btypes, scress, counts, amounts, stores, sumAmounts amount = 10000 start = '' end = '' tcode = sys.argv[1] if len(sys.argv) > 2: amount = sys.argv[2] if len(sys.argv) > 3: start = sys.argv[3] if len(sys.argv) > 4: end = sys.argv[4] cent = trade(tcode, begin=start, end=end, balance=amount) df = cent.data df['buy'], df['scress'], df['counts'], df['amounts'], df['store'], df[ 'sumAmount'] = fitter(df) df['date'] = numpy.array(df.index) print(df.to_json(orient='records'))
try: if api.connect(ip, 7709): return except: pass connect(api) if __name__ == '__main__': userid = os.environ.get('userid', "test1") buylist = eval(os.environ.get('buylist', "[]")) selllist = eval(os.environ.get('selllist', "[]")) query = os.environ.get("query", False) trader = trade(UserID=userid, api=api, mock=True) accountinfo, holdlists = trader.position() if query: logger.info(accountinfo.to_dict('records')) logger.info(holdlists.to_dict('records')) else: if holdlists.shape[0] > 0: holdlists.set_index("证券代码", inplace=True) for stock, number in buylist: logger.info("buy: {} number:{}".format(stock, number)) trader.buy(stock, int(number)) for stock, number in selllist: try: h_number = holdlists.ix[stock]["参考持股"]
import numpy as np import csv from trade import trade from dqn_agent import DQNAgent from datetime import datetime as dt if __name__ == "__main__": # parameters n_epochs = 10000 # environment, agent env = trade() agent = DQNAgent(env.enable_actions) #histrical data f = open('./data/USDJPY1_201810.csv', 'r') reader = csv.reader(f) header = next(reader) HisData = [] for row in reader: HisData.append(row) #log file fout = open('./logs/train_log.txt', 'w') # variables prft = 0 for e in range(n_epochs): cnt = 0 loss = 0
ship = UNI.ships[current_player.ship_current] print(f"Cargo: {ship['cargo']}\n Wallet: {current_player.wallet}") elif command == 'S': utils.scanner(current_player.current_node, UNI) elif command == 'P': node_data = UNI.graph.node[current_player.current_node] station = node_data.get('station', None) if station is not None: selection = '' print("\n<T> Trade at this Port\n<Q> Quit, nevermind") while selection.upper() not in ['T', 'Q']: selection = input('Enter your choice? ') if selection.upper() == 'T': trade(UNI, current_player, station) elif command == '?': print("\n This is the help menu. P to trade at a Port, Q to quit, V to view jump history. C to show your wallet and cargo. S to use the scanner on planets and stars.") else: print("Invalid command!") pickle.dump(UNI, open(UNI_PATH, 'wb')) r.publish('GAMEWORLD', '{} leaves the game...'.format(current_player.name)) p.unsubscribe() print(UNI.players)
#t = bitcoin_ticker(content.decode("utf-8")) #t.update(); # TO DEBUG #pdb.set_trace() link_thicker = "https://www.mercadobitcoin.com.br/api/trades/" c = pycurl.Curl() c.setopt(c.URL,link_thicker) storage = io.BytesIO() c.setopt(c.WRITEFUNCTION,storage.write) c.perform() c.close() content = storage.getvalue().decode("utf-8") tr = trade(content) link_thicker = "https://www.mercadobitcoin.com.br/api/orderbook/" c = pycurl.Curl() c.setopt(c.URL,link_thicker) storage = io.BytesIO() c.setopt(c.WRITEFUNCTION,storage.write) c.perform() c.close() content = storage.getvalue().decode("utf-8") order = orderbook(content) link_thicker = "https://www.mercadobitcoin.com.br/api/trades_litecoin/" c = pycurl.Curl() c.setopt(c.URL,link_thicker) storage = io.BytesIO()
def main(): try: print("\n>> CoinAnalyze v0.7 by cloud <<\n\n") sendMessageTelegram("Coin Analyzer Bot v0.7 Started") ##### TRADE MODULE####### trading = 0 tr = trade() if trading == 1: print("Trading module : On") sendMessageTelegram("Trading module : On") end = 0 else: print("Trading module : Off") sendMessageTelegram("Trading module : Off") ######################### #We initialize the different timer timer1hnext = (datetime.now() + timedelta(seconds=3600)).hour timer20mnnext = (datetime.now() + timedelta(seconds=60)) while (int(str(timer20mnnext.minute)) % 20) != 0: timer20mnnext = timer20mnnext + timedelta(seconds=60) market = coinmarketcap() binancecoin = binance() listcoin = [] ticker = {} ticker = binancecoin.checkTicker() symbol = binancecoin.getListSymbol(ticker) #We create an object by coin for c in symbol: coinC = coin(c) listcoin.append(coinC) while True: time.sleep(1) timer = datetime.now() ####### EVERY 1H ############### if timer.hour == timer1hnext: print(timer) if trading == 1: msg = tr.summaryTrade() print(msg) sendMessageTelegram(msg) timer1hnext = (datetime.now() + timedelta(seconds=3600)).hour ### We check General coinmarketcap every 60mn market.checkGlobal() checkmarket = market.analyze_total_market_cap_eur() #Analyze Market msg = "" msg = msg + printcheckmarket(market, checkmarket) msg = msg + "\n" checkmarket = market.analyze_bitcoin_percentage_of_market_cap() msg = msg + printbtcdominance(market, checkmarket) print(msg) sendMessageTelegram(msg) msg = "" ####### EVERY 20mn ############### ## New Symbol check timer20mn = datetime.now() period = ['1h', '4h', '1d'] if ((int(timer20mn.minute) % 20) == 0) and (timer20mnnext.minute == timer20mn.minute): #if 1 == 1: if trading == 1: period = ['1h', '4h', '1d'] timer20mnnext = (datetime.now() + timedelta(seconds=12000)) ####### ACTION ################### for p in period: msg = "" #On récupère les infos de chaque coin sur une période de 252 et on les ajoute à chaque coin pour gérer les alertes listAllValues = [] listAllValues = binancecoin.checkAllInfoValues(p) for c in listAllValues: for x in listcoin: end, msg = tr.checkEndTrade() if end == 1: print(msg) sendMessageTelegram(msg) trading = 0 period = ['4h', '1d'] if c['symbol'] == x.getSymbol(): x.setValues(c) if trading == 1: stoploss = tr.stopLoss(x) if stoploss == 1: msg = "STOP LOSS (5%) for " + x.getSymbol( ) print(msg) sendMessageTelegram(msg) if p != '1h': #RSI must be the first test to set RSI for the PRS test #RSI alert check rsi = x.rsiAlert(p) if rsi != 0: msg = printRSIAlert( x.getSymbol(), rsi, p) print(msg) #sendMessageTelegram(msg) msg = "" #RSI DIV Alert rsidiv, price = x.rsiDivAlert(p) if rsidiv != 0: msg = msg + printRSIDIVAlert( x.getSymbol(), rsidiv, p, price) print(msg) sendMessageTelegram(msg) msg = "" #if trading == 1: # restrade,msg = tr.buysell(rsidiv, x.getSymbol(), price) # print msg # sendMessageTelegram(msg) #MACD alert check macd, price = x.macdAlert(p) if macd != 0: msg = printMACDAlert( x.getSymbol(), macd, p, price) print(msg) #sendMessageTelegram(msg) msg = "" #PRS Alert prs, price = x.prsAlert(p) if prs != 0: msg = printAlert( "PRS", x.getSymbol(), prs, p, price) print(msg) #sendMessageTelegram(msg) msg = "" #if trading == 1: # restrade,msg = tr.buysell(prs, x.getSymbol(), price) # print msg # sendMessageTelegram(msg) #Nightou Alert nightou, price = x.nightouAlert(p) if nightou != 0: msg = msg + printNightouAlert( x.getSymbol(), p, price) print(msg) sendMessageTelegram(msg) msg = "" if trading == 1: restrade, msg = tr.buysell( nightou, x.getSymbol(), price) print(msg) sendMessageTelegram(msg) #ADX Alert adx, price = x.adxAlert(p) if adx != 0: msg = msg + printAlert( "ADX", x.getSymbol(), adx, p, price) print(msg) #sendMessageTelegram(msg) msg = "" #if trading == 1: # restrade,msg = tr.buysell(adx, x.getSymbol(), price) # print msg # sendMessageTelegram(msg) #CCI Alert cci, price = x.cciAlert(p) if cci != 0: msg = msg + printAlert( "CCI", x.getSymbol(), cci, p, price) print(msg) #sendMessageTelegram(msg) msg = "" #if trading == 1: # restrade,msg = tr.buysell(cci, x.getSymbol(), price) # print msg # sendMessageTelegram(msg) #CLOUD Alert cloud, price = x.cloudStrategy(p) if cloud != 0: msg = msg + printAlert( "CLOUD", x.getSymbol(), cloud, p, price) print(msg) sendMessageTelegram(msg) msg = "" if trading == 1: restrade, msg = tr.buysell( cloud, x.getSymbol(), price) print(msg) sendMessageTelegram(msg) #EMA Alert ema, price = x.emaStrategy(p) if ema != 0: msg = msg + printAlert( "EMA", x.getSymbol(), ema, p, price) print(msg) sendMessageTelegram(msg) msg = "" if trading == 1: restrade, msg = tr.buysell( ema, x.getSymbol(), price) print(msg) sendMessageTelegram(msg) ####### NEW SYMBOL ######### ticker = binancecoin.checkTicker() newsymbol = [] newsymbol = binancecoin.getNewSymbol() for c in newsymbol: coinC = coin(c) listcoin.append(coinC) msg = printNewSymbol(newsymbol) if msg != "": sendMessageTelegram(msg) print(msg) except (KeyboardInterrupt, SystemExit): sendMessageTelegram("Maintenance, I'll be back soon") return 0
timesd3mo, movingsd3mo = f.movingsd(priceratio, longavgtime, timeratio) timeavg3mo, movingavg3mo = f.movingavg(priceratio, longavgtime, timeratio) timeavg5d, movingavg5d = f.movingavg(priceratio, shortavgtime, timeratio) low1, high1 = f.sdbounds(movingavg3mo, movingsd3mo, uppersigma) zscoree = f.zscore(movingavg5d, movingavg3mo, movingsd3mo) when, whenlist = f.whentotrade(zscoree, timeavg3mo, cor252, uppersigma) #print("Cointigration Value: "+str(f.cointigration(price1,price2))) #instantiates trade objects trades = [] for tradetime in when: location = np.sign(zscoree[f.indexoftime(timeavg3mo, tradetime)]) trades.append( trade.trade(price1, price2, time1, tradetime, location)) trades[len(trades) - 1].set_inputamount(1000) totalreturns = 0 for q in range(len(trades)): starttime = trades[q].get_starttime() startindex = f.indexoftime(timeavg3mo, starttime) timezscore = timeavg3mo[startindex:] zscoreupdate = zscoree[startindex:] sigbounds = lowersigma for qq in range(len(zscoreupdate) - 2): trades[q].exittrade(timezscore[qq + 2]) if trades[q].get_totalreturns() < -100: #print("RETURNS BELOW -100") starttt = trades[q].get_starttime() #print("index: "+str(q))
# -*- coding: utf-8 -*- """ Created on Mon May 9 21:56:05 2016 @author: way """ import sys sys.path.append("/data/pyquant/signal") import flag import zxb_limit import easytrader as et from easydealutils import time as ed import trade import time import os from strategy import cser import feed import multiprocessing from tradable import * user = et.use("ht") user.prepare("/data/pyquant/ht.json") account_flag = flag.flag() chiyou_feed = feed.feed("chicang") chicang_trade = trade.trade(chiyou_feed.load(), user) chicang_trade.stop() account_flag.set_flag(4)
# 根据macd值买入优化v1.0.0 2020.7.14 # 步骤: # 1.获取 MACD DEA,DIFF # 2.如果 MACD>0 --其实也就是20日均线开始向上掉头,判断是否可以买入 # 3.以第一次买入价制定买卖价格11个档位 -- 30日均线 向上5个,向下五个 各以5%为阶梯 # 4.循环判断买入条件 # 1 MACD>0 # 2 b 股价在30日均线1%以内 # 3 股价在当前档位没有持仓 # 5. 卖出条件 # 1 股价超过持仓最低档卖出价 buylogs = [] selllogs = [] plandf = pd.DataFrame() tradecenter = trade() def makeplan(price): # 创建购买计划 logging.info("创建购买计划:%s",price) input = pd.Series(np.logspace(-9, 1, 10, base=1.05)*price) tem = (pd.Series(np.arange(24, 14, -1))*0.01) out = (tem +1)*input global plandf plandf = pd.DataFrame({ "input": input, "out": out, "store":0, "tem":tem}) logging.info("购买计划创建完毕\n%s",plandf) def getbuyprice(): # 获取购买价格 return plandf[plandf.store == 0].input.max()
def init(args): states, last_datapoints = get_initial_states(args.sequence_length, args.interval_length) # Restore trained model session = tf.Session() ckpt_file = '' if not args.model_file: ckpt_file = tf.train.latest_checkpoint(MODEL_DIR) else: ckpt_file = args.model_file meta_graph = tf.train.import_meta_graph(ckpt_file + '.meta') meta_graph.restore(session, ckpt_file) graph = tf.get_default_graph() inputs = graph.get_tensor_by_name(trainer.INPUT_PLACEHOLDER + ':0') labels = graph.get_tensor_by_name(trainer.LABEL_PLACEHOLDER + ':0') pred = graph.get_tensor_by_name(trainer.OUTPUT_LAYER + ':0') db = MySQLdb.connect(db=constants.MYSQL_DB_NAME, host=constants.MYSQL_HOST, user=api_access_data.MYSQL_USER, passwd=api_access_data.MYSQL_PASSWD) db.autocommit(True) while (True): predictions = [] for (product_idx, (state, product)) in enumerate(zip(states, PRODUCTS)): crypto_labels = np.zeros((1, args.sequence_length)) crypto_labels.fill(product_idx) prediction = session.run([pred], { inputs: state, labels: crypto_labels }) prediction = np.squeeze(prediction).item() * 100 predictions.append((prediction, product)) print('Product: %s Trend prediction: %f%%' % (product, prediction)) if args.test: print('In test mode: not performing trades. Check grafana for ' 'performance metrics') else: # Process the predictions in order of magnitude of change predictions.sort(key=lambda x: abs(x[0])) for (prediction, product) in predictions: cursor = db.cursor() trade.trade(prediction, product, cursor) time.sleep(args.interval_length * 60) # Get new data for (idx, product) in enumerate(PRODUCTS): # Prevent rate limiting if (idx > 0): time.sleep(1) new_datapoint = get_last_x_interval_data(product, 1, args.interval_length) new_datapoint = np.squeeze(new_datapoint) new_datapoint, last_datapoints[idx] = ( (new_datapoint / last_datapoints[idx]) - 1, new_datapoint) current_trend = new_datapoint[-2] new_datapoint = new_datapoint.reshape(1, 1, new_datapoint.shape[0]) states[idx] = np.concatenate( (states[idx][:, 1:, :], new_datapoint), axis=1) current_trend *= 100 prediction = list(filter(lambda x: x[1] == product, predictions))[0][0] write_prediction_to_influxdb(prediction, current_trend, product) print('Product: %s Acutal trend: %f%%; Last prediction: %f%%' % (product, current_trend, prediction))
def recordTrade(self, timeStamp, quantity, buySellIndicator, price): trades = trade(timeStamp, quantity, buySellIndicator, price) self.record.append(trades)
def main(argv): horizontal_line = "-------------------------" print(horizontal_line * 2) print("DAT602-assignment3 crypto-trading demo.") print("Please wait while initializing the database...") gdax = gw.gdax_websocket() gdax.start() time.sleep(1) ledger = Ledger(100000000) print("$" + str(ledger.get_current_cash()) + " available to start trading.") print(horizontal_line * 2) fini = False while not fini: menu() choice = input(">>>>> Please select the menu: \n>") if choice == "6": # Quit fini = True gdax.stop() elif choice == "5": # Show P/L Chart print(horizontal_line * 3) print("<<P/L Line Chart>>") print(horizontal_line * 3) try: pl_data = ledger.get_pl_cache() pldisp.pl_display(pl_data) print("Should the graph fails to load in the browser,") print( "Please click: https://plot.ly/~silverrainb/10/vwap-executedprice-total-pl-cash/" ) print(horizontal_line * 3) except KeyError: print( "No transactions have been performed to display the history" ) print(horizontal_line * 3) elif choice == "4": # Show P/L Records print(horizontal_line * 3) print("<<P/L Records>>") print(horizontal_line * 3) try: pl_data = ledger.get_pl_cache() print(pl_data) except KeyError: print( "No transactions have been performed to display the history" ) elif choice == "3": # Show P/L print(horizontal_line * 3) print("<<P/L>>") print("Please hold while calculating forecast...") print(horizontal_line * 3) ledger.update_positions(gdax) print(horizontal_line * 3) elif choice == "2": # Show Blotter print(horizontal_line * 3) print("<<Blotter>>") print(horizontal_line * 3) try: blotter = ledger.get_blotter() print(blotter) except KeyError: print( "No transactions have been performed to display the history" ) print(horizontal_line * 3) elif choice == "1": # Trade trade.trade(ledger, gdax) print(">>>>> Goodbye!")