def __start_trade_for_user(self, user): print("Start trade for %s" % user["UserName"]) trader = Trader(user, self.__mq) trader.start_trade() print("End the trade for %s" % user["UserName"])
} } } secrets_content = get_json_from_file(secrets_file_directory, secrets_template) if secrets_content == secrets_template: print("Please completed the `secrets.json` file in your `database` directory") exit() return secrets_content if __name__ == "__main__": secrets = get_secrets() Messenger = Messenger(secrets) Trader = Trader(secrets) Trader.initialise() while True: try: Trader.analyse_pauses() Trader.analyse_buys() Trader.analyse_sells() time.sleep(10) except SSLError as exception: Messenger.print_exception_error("SSL") logger.exception(exception) time.sleep(10) except ConnectionError as exception:
def main(): traders = [] traders.append(Trader(CoinCheck, None, "CoinCheck: ")) traders.append(Trader(Zaif, None, " Zaif: ")) traders.append(Trader(BitFlyer, None, " bitFlyer: ")) first_rate = {} last_rate = {} last_balance = {} for trademan in traders: trademan.deposit(brand="jpy", money=Capital) trademan.buyMaxOfBalance(pair="btc_jpy") date = datetime.now().strftime("%m-%d %H:%M:%S") name = trademan.name rate = trademan.getRate("btc_jpy") amount = trademan.volume["btc"] first_rate[name] = rate last_rate[name] = rate last_balance[name] = trademan.getBalance() print("{date}\t{name} BUY {rate} {amount}".format(**locals())) while True: date = datetime.now().strftime("%m-%d %H:%M:%S") for trademan in traders: rate = trademan.getRate("btc_jpy") last = trademan.rate["btc"] name = trademan.name ratio = (rate - trademan.rate["btc"]) * 100 / trademan.rate["btc"] if rate < last: # 売ったときより安くなれば買う if trademan.balance["jpy"] > rate * One_Satoshi: # 予算の有無 trademan.buyMaxOfBalance(pair="btc_jpy") amount = trademan.volume["btc"] print("{date}\t{name} BUY {rate} {amount}".format( **locals())) elif rate >= last and ratio > 0.05: # 利益が0.05%以上になったら売る if trademan.volume["btc"] > One_Satoshi: # 売るものがあるか確認 benefit = (rate - trademan.rate["btc"]) * trademan.volume["btc"] trademan.sellAll("btc_jpy") print("{date}\t{name}SELL ".format(**locals()) + "{0:+10.3f}\t{1:+5f}%".format(benefit, ratio)) # 現在の価値 print(date, end="\t") for trademan in traders: balance = trademan.getBalance() if balance >= last_balance[trademan.name]: print(Fore.GREEN + "{:10.3f}".format(balance) + Fore.RESET, end=" ") else: print(Fore.RED + "{:10.3f}".format(balance) + Fore.RESET, end=" ") last_balance[trademan.name] = trademan.getBalance() print("| ", end="") # 現在の価格 for trademan in traders: rate = trademan.getRate("btc_jpy") if rate >= last_rate[trademan.name]: print(Fore.GREEN + "{:10.3f}".format(rate) + Fore.RESET, end=" ") else: print(Fore.RED + "{:10.3f}".format(rate) + Fore.RESET, end=" ") last_rate[trademan.name] = trademan.getRate("btc_jpy") print("| ", end="") # 最初の価格との差 for trademan in traders: diff = last_rate[trademan.name] - first_rate[trademan.name] if diff >= 0: print(Fore.GREEN + "{:+10.3f}".format(diff) + Fore.RESET, end=" ") else: print(Fore.RED + "{:+10.3f}".format(diff) + Fore.RESET, end=" ") print("| ", end="") # 現在の価値 - 最初に買ってからホールドした時の金額 for trademan in traders: diff = last_balance[trademan.name] - Capital * last_rate[ trademan.name] / first_rate[trademan.name] if diff >= 0: print(Fore.GREEN + "{:+10.3f}".format(diff) + Fore.RESET, end=" ") else: print(Fore.RED + "{:+10.3f}".format(diff) + Fore.RESET, end=" ") print("") time.sleep(9)
def main(): if args.strategy == "classic": test = Sig("tn", 1451793600, "BTC", 1.1, 42, "BUY") CandleFetcher.update_tables(table_names.short_term_tables) trader = Trader(Trader.CLASSIC) trader.run()
def test_resize(g=True): #Create the exchange ex = Exchange('DEX', 'address', 1_000) # Create the order book book = test_book() # Add the order book to the exchange ex.add_book(book) # Create the graph object graph = Graph() graph.exchange = ex # Create 10 traders n = 10 bidders = [] askers = [] # Create the N traders with bids for x in range(0, n): bidders.append(Trader(f'bidder {x}')) bidders[x].new_order( 'buy', (x + 1) * 100, # p_high 80, # p_low 1000, # u_max 2000) # q_max ex.get_order(bidders[x].current_order) # Create the N traders with asks and send to exchange for x in range(0, n): askers.append(Trader(f'asker {x}')) askers[x].new_order( 'sell', (x + 1) * 100, # p_high 80, # p_low 1000, # u_max 2000) # q_max ex.get_order(askers[x].current_order) # Process any messages in the book's queue while len(ex.book.message_queue) > 0: ex.book.process_messages() ex.book.pretty_book() # Hold the batch ex.hold_batch() # Graph the default schedules, p_high = 1000 if g: graph.graph_all_aggregates(1, 'r', 'b') graph.graph_total_aggregates(2, 'r', 'b', 'g-') # Create a new trader with a p_high double max_price big_bidder = Trader('Big Bidder') big_bidder.new_order('buy', 2000, 80, 1000, 2000) ex.get_order(big_bidder.current_order) # Process the new message while len(ex.book.message_queue) > 0: ex.book.process_messages() ex.book.pretty_book() # Hold the batch ex.hold_batch() if g: graph.graph_all_aggregates(3, 'r', 'b') graph.graph_total_aggregates(4, 'r', 'b', 'g-') # Cancel the order with a high p_high # big_bidder.new_order('C', None, None, None, None) big_bidder.new_order('buy', 1500, 80, 1000, 2000) ex.get_order(big_bidder.current_order) # Process the new message while len(ex.book.message_queue) > 0: ex.book.process_messages() ex.book.pretty_book() # Hold the batch ex.hold_batch() if g: graph.graph_all_aggregates(5, 'r', 'b') graph.graph_total_aggregates(6, 'r', 'b', 'g-') graph.display()
import sys import time import MetaTrader5 as mt5 import schedule from strategy_utils import load_strategy from trader import Trader def trade(trader): schedule.every().hour.at(":00").do(trader.run, mt5.TIMEFRAME_M15) schedule.every().hour.at(":15").do(trader.run, mt5.TIMEFRAME_M15) schedule.every().hour.at(":30").do(trader.run, mt5.TIMEFRAME_M15) schedule.every().hour.at(":45").do(trader.run, mt5.TIMEFRAME_M15) while True: schedule.run_pending() time.sleep(1) if __name__ == '__main__': # Create strategy strategy = sys.argv[1] print(f"Trader started with strategy: {strategy}") strategy_json = load_strategy(strategy) trader = Trader(41452978, strategy_json) trade(trader)
import bitmex import time from configuration import * from strategy import Strategy from trader import Trader if __name__ == "__main__": client = bitmex.bitmex(test=TEST_EXCHANGE, api_key=API_KEY, api_secret=API_SECRET) strategy = Strategy(client, timeframe=TIMEFRAME) trader = Trader(client, strategy, money_to_trade=AMOUNT_MONEY_TO_TRADE, leverage=LEVERAGE) while True: if round(time.time()) % time_to_wait_new_trade[TIMEFRAME] == 0: trader.execute_trade() time.sleep(5) # 10
# from portfolio import Portfolio # p = Portfolio() # p.inject(500) # print(p.get_value()) from trader import Trader t = Trader() print(t.portfolio.liquid) print(t.buy('TICK', 5)) print(t.sell('TICK', 1)) print(t.get_holdings()) print(t.get_pl())
def __init__(self): self.trader = Trader() self.markets = settings.MARKETS self.coins = settings.COINS
def doTrade(pool, afmt, af, as1mt, as1, as2mt, as2): global std, prices #sname = str(stdPeriod) + '_' + str(stdGuage) sname = afmt + '_' + str(af) + '_' + as1mt + '_' + str(as1) if as2 > 0: sname += '_' + as2mt + '_' + str(as2) if const.currentSecId: sname = const.currentSecId + '_' + sname afma, as1ma, as2ma = getMas(afmt, af), getMas(as1mt, as1), getMas(as2mt, as2) front = max(as1, as2) active = 0 a1pos = a2pos = 0 a1wait = a2wait = 0 a1price = a2price = 0 t = Trader(sname) for i in range(front, len(prices)): price = prices[i] volume = 0 notes = '' oa1pos, oa2pos = a1pos, a2pos oa1wait, oa2wait = a1wait, a2wait #A if as1 > 0 and afma[i - 1] <= as1ma[i - 1] and afma[i] > as1ma[i]: a1wait = 1 if as1 > 0 and afma[i - 1] >= as1ma[i - 1] and afma[i] < as1ma[i]: a1wait = -1 if as2 > 0 and afma[i - 1] <= as2ma[i - 1] and afma[i] > as2ma[i]: a2wait = 1 if as2 > 0 and afma[i - 1] >= as2ma[i - 1] and afma[i] < as2ma[i]: a2wait = -1 if const.DIRECTION == 1 and a1wait == -1: a1wait = 0 if const.DIRECTION == 1 and a2wait == -1: a2wait = 0 a1pos, a2pos = a1wait, a2wait if oa1pos != a1pos: volume += a1pos - oa1pos notes += 'A1:' + str(oa1pos) + '->' + str(a1pos) + ';' + str( a1price) + '->' + str(price['trade']) + ';' a1price = price['trade'] if oa2pos != a2pos: volume += a2pos - oa2pos notes += 'A2:' + str(oa2pos) + '->' + str(a2pos) + ';' + str( a2price) + '->' + str(price['trade']) + ';' a2price = price['trade'] if volume != 0: t.processOrder(price['dt'], price['trade'], volume * 1000, notes=notes) else: t.summary(price['dt'], price['trade']) pool.estimate(t) return t
settings_template) if settings_content == settings_template: print( "Please completed the `settings.json` file in your `database` directory" ) exit() return settings_content if __name__ == "__main__": secrets = get_secrets() settings = get_settings() Messenger = Messenger(secrets, settings) Trader = Trader(secrets, settings) Trader.initialise() while True: try: Trader.analyse_pauses() Trader.analyse_buys() Trader.analyse_sells() time.sleep(10) except SSLError as exception: Messenger.print_exception_error("SSL") logger.exception(exception) time.sleep(10) except ConnectionError as exception:
import os import sys from trader import Trader api_key = os.environ['BINANCE_API_KEY'] api_secret = os.environ['BINANCE_API_SECRET'] quote = sys.argv[1] if len(sys.argv) > 1 else "USDT" assetsConfig = sys.argv[2] if len(sys.argv) > 2 else "assets.test.txt" Trader(api_key, api_secret, quote, assetsConfig, True).tune(assetsConfig)
def default_trader(): '''Returns a trader object with balance 0.0''' return Trader('account name')
# coding: utf-8 import sys from ctpwrapper import ApiStructure from ctpwrapper import MdApiPy from ctpwrapper import TraderApiPy from trader import Trader, Trader_FUTURES from md import Md, Md_PRICE import time import CONST import asyncio md = Md(CONST.BORDKER_ID, CONST.INVESTOR_ID, CONST.PASSWORD) trader = Trader(CONST.BORDKER_ID, CONST.INVESTOR_ID, CONST.PASSWORD) md.Create() md.RegisterFront(CONST.MD_SERVER) md.Init() trader = Trader(CONST.BORDKER_ID, CONST.INVESTOR_ID, CONST.PASSWORD) trader.Create() trader.RegisterFront(CONST.TD_SERVER) trader.SubscribePrivateTopic(2) trader.Init() def ctp_handle(result): """ 0: 发送成功 -1: 因网络原因发送失败
def doTrade(pool, vfmt, vf, vsmt, vs, afmt, af, as1mt, as1, bfmt, bf, bs1mt, bs1): global prices sname = vfmt + '_' + str(vf) + '_' + vsmt + '_' + str(vs) sname += '_' + afmt + '_' + str(af) + '_' + as1mt + '_' + str(as1) sname += '_' + bfmt + '_' + str(bf) + '_' + bs1mt + '_' + str(bs1) if const.currentSecId: sname = const.currentSecId + '_' + sname vfma, vsma = getVmas(vfmt, vf), getVmas(vsmt, vs) afma, as1ma = getMas(afmt, af), getMas(as1mt, as1) bfma, bs1ma = getMas(bfmt, bf), getMas(bs1mt, bs1) front = max(vs, as1, bs1) active = 0 a1pos = b1pos = 0 a1wait = b1wait = 0 a1price = b1price = 0 t = Trader(sname) t.args = [afmt, af, as1mt, as1, bfmt, bf, bs1mt, bs1] for i in range(front, len(prices)): price = prices[i] active = 'A' if vfma[i] > vsma[i]: active = 'B' volume = 0 notes = '' oa1pos, ob1pos = a1pos, b1pos oa1wait, ob1wait = a1wait, b1wait #A if as1 > 0 and prices[i]['close'] > prices[ i - 1]['close'] and afma[i] > afma[i - 1] and afma[ i - 1] <= as1ma[i - 1] and afma[i] > as1ma[i]: a1wait = 1 if as1 > 0 and afma[i - 1] >= as1ma[i - 1] and afma[i] < as1ma[i]: a1wait = -1 if bs1 > 0 and prices[i]['close'] > prices[ i - 1]['close'] and bfma[i] > bfma[i - 1] and bfma[ i - 1] <= bs1ma[i - 1] and bfma[i] > bs1ma[i]: b1wait = 1 if bs1 > 0 and bfma[i - 1] >= bs1ma[i - 1] and bfma[i] < bs1ma[i]: b1wait = -1 if const.DIRECTION == 1 and a1wait == -1: a1wait = 0 if const.DIRECTION == 1 and b1wait == -1: b1wait = 0 if a1wait == 0: a1pos = 0 elif active == 'A' and a1wait != oa1wait: a1pos = genVolume(price['trade'], a1wait) if b1wait == 0: b1pos = 0 elif active == 'B' and b1wait != ob1wait: b1pos = genVolume(price['trade'], b1wait) if oa1pos != a1pos: volume += a1pos - oa1pos notes += 'A1:' + str(oa1pos) + '->' + str(a1pos) + ';' + str( a1price) + '->' + str(price['trade']) + ';' + 'afma:' + str( afma[i - 1]) + '->' + str(afma[i]) + ';as1ma:' + str( as1ma[i - 1]) + '->' + str(as1ma[i]) + ';' a1price = price['trade'] if ob1pos != b1pos: volume += b1pos - ob1pos notes += 'B1:' + str(ob1pos) + '->' + str(b1pos) + ';' + str( b1price) + '->' + str(price['trade']) + ';' + 'afma:' + str( bfma[i - 1]) + '->' + str(bfma[i]) + ';bs1ma:' + str( bs1ma[i - 1]) + '->' + str(bs1ma[i]) + ';' b1price = price['trade'] if volume != 0: t.processOrder(price['dt'], price['trade'], volume, notes=notes) else: t.summary(price['dt'], price['trade']) pool.estimate(t) return t
def load_trader_from_props(props_str): account = json.loads(props_str)['exchangeAccount'] return Trader(account['accountId'], account['privateKey'])
def load_config(): traders = [] config = configparser.RawConfigParser() config.read('.config') sections = config.sections() for name in sections: indicator = config.get(name, 'indicator') public_key = config.get(name, 'public key') private_key = config.get(name, 'private key') exchange = config.get(name, 'exchange') pair = config.get(name, 'pair') amount = config.getfloat(name, 'amount') charting = 'candlestick' initial_wait = 5 period_length = 60 update_interval = 5 secondary_indicator = None #configure optional arguments in the config if config.has_option(name, 'charting'): charting = config.get(name, 'charting') if config.has_option(name, 'initial_wait'): initial_wait = config.getint(name, 'initial_wait') if config.has_option(name, 'period_length'): period_length = config.getint(name, 'period_length') if config.has_option(name, 'update_interval'): update_interval = config.getint(name, 'update_interval') if config.has_option(name, 'secondary_indicator'): secondary_indicator = config.get(name, 'secondary_indicator') trader = Trader(name,\ exchange,\ public_key,\ private_key,\ pair,\ amount,\ charting=charting,\ initial_wait=initial_wait,\ period_length=period_length,\ update_interval=update_interval\ ) traders.append(trader) if indicator == 'smacrossover': if config.has_option(name, 'short') and config.has_option( name, 'long'): ssma = config.getint(name, 'short') lsma = config.getint(name, 'long') trader.config_sma(ssma, lsam) else: trader.config_sma() trader.set_indicator('sma_crossover') elif indicator == 'emacrossover': if config.has_option(name, 'short') and config.has_option( name, 'long'): sema = config.getint(name, 'short') lema = config.getint(name, 'long') trader.config_ema(sema, lema) else: trader.config_ema() trader.set_indicator('ema_crossover') elif indicator == 'donchianbreakout': if config.has_option(name, 'parameter'): para = config.getint(name, 'parameter') trader.config_donchian_channels(para) else: trader.config_donchian_channels() trader.set_indicator('donchian_breakout') else: print("Error in Config file. The indicator is not valid. Exiting.") exit() return traders
import PySimpleGUI as sg from utils.cfg import Settings from trader import Trader trader = Trader() from utils.logger import Lgr from output import output from input_parser import get_order_param from input_parser import get_plan_order_param sg.theme('DarkAmber') big_font = "Helvetica 25" mid_font = "Helvetica 20" sml_font = "Helvetica 15" ######################################################################################################## ############## 界面元素 ############# # 账户信息 acct_cb_list = [sg.Text('账号:', font=mid_font)] for acct in Settings['accts']: item = sg.Checkbox(f"{acct['name']}", default=True, key=f"acct-{acct['name']}", font=mid_font) acct_cb_list.append(item) # 下单参数设置 # 开仓数值比例 mr_radios = [sg.Text('开仓保证金比:')] for mr in Settings['margin_ratio']: dft = True if mr=='5%' else False mr_radios.append(sg.Radio(mr, 'mr', default=dft, font=mid_font, key=f'mr-{mr}'))
from account_data_retriever import AccountDataRetriever from flask import Flask, render_template from webpage_data_refresher import WebpageDataRefresher from trader import Trader import csv T = Trader() data = T.create_market_order_data("AMD", 5, "buy", "market", "day") #T.place_order(data) app = Flask(__name__) def ticker_dict(): company_industry = {} with open('symbols.csv', 'r') as csvfile: reader = csv.reader(csvfile) for row in reader: company_industry[row[1]] = row[2].replace(' ', '_') return company_industry @app.route("/") def index(): WDR = WebpageDataRefresher() WDR.create_site_html() stocks = WDR.positions sorted_by_plpc = WDR.plpc_sorted_holdings ADR = AccountDataRetriever() cats = ADR.get_cats()
def __init__(self, name, config): self.cycles = 0 self.config = config self.name = name self.budget = config.get("budget", 0) self.initial_budget = self.budget self.tradelimit = config.get("tradelimit", 0) self.market = config.get("market", None) self.candlesize = config.get("candlesize", "1h") self.timeframe = config.get("timeframe", "1d") self.basesize = config.get("basesize", "1m") if not self.market: raise Exception( "missing required fields market: {}, budget: {}, tradelimit: {}" .format(self.market, self.budget, self.tradelimit)) if "usdt" in self.market.lower(): self.scale = config.get("scale", "2") else: self.scale = config.get("scale", "8") self.tcpsock = None # move this functionality to wallet class self.growth_target = config.get("growthtarget", 2) self.stop_loss = config.get("stoploss", 3) self.signal = None self.results = {} #dataprovider for candlestick data self.trader = Trader(market=self.market) #candlestick data self.csdata = None #manage indicators self.analyzer = None #manage orders self.ordermanager = None #keep track of latest indicator and bot signals self.signal_history = {} self.all_signals = [] self.log = logging.getLogger('crypto') # debug messages passed to bot client self.debug = [] #aggregate bot data for bot client self.data_provider = BotDataProvider(self) #enable backtesting... self.backtest = config.get("backtest", False) if "backtest_start_time" in config: ts = config["backtest_start_time"] else: ofs = config.get("backtest_start_ofs", 259200) ts = time.time() - ofs ts = ts - (ts % 3600) - config.get("run_offset", 0) self.backtest_tick = ts self.backtest_startprice = None self.backtest_endprice = 0 self.run_interval = config.get("run_interval", 300) if self.backtest: random.seed() rid = random.randint(100, 70000) self.name = "{}-{}".format(name, rid)
from datastore import ArcticStore from saver import PickleSaver from blotter import CsvBlotter from trader import Manager, Trader from portfolio import FixedPortfolio, AdjustedPortfolio from strategy import strategy_kwargs log = logger(__file__[:-3], WARNING, WARNING) start_date = '20180601' end_date = '20191231' cash = 80000 store = ArcticStore('TRADES_30_secs') source = DataSourceManager(store, start_date, end_date) ib = IB(source, mode='db_only', index=-2) # mode is: 'db_only' or 'use_ib' util.logToConsole() asyncio.get_event_loop().set_debug(True) blotter = CsvBlotter(save_to_file=False, filename='backtest', path='backtests', note=f'_{start_date}_{end_date}') saver = PickleSaver('notebooks/freeze/backtest') trader = Trader(ib, blotter) manager = Manager(ib, saver=saver, trader=trader, **strategy_kwargs) market = Market(cash, manager, reboot=False) ib.run() blotter.save() manager.freeze()
# unit tests eg for crossabove and crossunder # todo - cater for different strategies # todo - add image to slack message logger = logging.getLogger('cryptobot') logger.setLevel(logging.DEBUG) handler = logging.handlers.WatchedFileHandler('cryptobot.log') handler.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s") handler.setFormatter(formatter) logger.addHandler(handler) logger.debug('Starting') api_key, api_secret = os.environ['BITMEX_API_KEY'], os.environ['BITMEX_API_SECRET'] client = bitmex.bitmex( test=True, api_key=api_key, api_secret=api_secret ) logger.debug('Connected to bitmex') strategy = MAStrategy(client, timeframe='1d', mas=1, mal=7) trader = Trader(client, strategy, money_to_trade=4000, leverage=1) trader.execute_trade() logger.info('Done')
def test_trader(): jason = Trader('jasons account', 100) order = jason.new_order('buy', 101, 99, 500, 10000) # cancel_order = jason.new_order('C', None, None, None, None) jason.describe() return jason
def q_learning(training_data, capital, num_episode=100, window_size=10): profits = [] for i in range(10): profit, series = random_action(training_data, capital) profits.append(profit) mean_profit = np.mean(profits) while profit > mean_profit: profit, series = random_action(training_data, capital) trader = Trader(window_size) num_step = len(training_data) - 1 starttime = time.time() for e in range(num_episode + 1): cumulative_reward = [] done = False state = state_normalize(training_data, 0, window_size + 1) total_profit = 0 trader.portfolio = [] x_data = range(num_step) for t in range(num_step): action = trader.act(state) next_state = state_normalize(training_data, t + 1, window_size + 1) reward = 0 # buy action if action == 1: if capital > training_data[t]: trader.portfolio.append(training_data[t]) capital -= training_data[t] # sell action elif action == 2: if len(trader.portfolio) > 0: bought_price = trader.portfolio.pop(0) reward = max(training_data[t] - bought_price, 0) total_profit += training_data[t] - bought_price capital += training_data[t] if t == num_step - 1: done = True trader.history.push(state, action, next_state, reward) state = next_state cumulative_reward.append(total_profit) trader.optimize() if total_profit == 0: try: trader.predict_net = torch.load('predict_model_backup', map_location=device) trader.target_net = torch.load('target_model_backup', map_location=device) except: return 0 else: torch.save(trader.predict_net, "predict_model_backup") torch.save(trader.target_net, "target_model_backup") if e % 10 == 0: trader.target_net.load_state_dict(trader.predict_net.state_dict()) torch.save(trader.predict_net, "predict_model") torch.save(trader.target_net, "target_model") plot_comparison(cumulative_reward, series)
def test_cancels(): ex = Exchange('DEX', 'address', 1_000) # Create the order book book = test_book() # Add the order book to the exchange ex.add_book(book) # Create the graph object graph = Graph() graph.exchange = ex n = 10 bidders = [] askers = [] # Create the N traders with bids for x in range(0, n): bidders.append(Trader(f'bidder {x}')) bidders[x].new_order( 'buy', (x + 1) * 100, # p_high 80, # p_low 1000, # u_max 2000) # q_max ex.get_order(bidders[x].current_order) # Create the N traders with asks and send to exchange for x in range(0, n): askers.append(Trader(f'asker {x}')) askers[x].new_order( 'sell', (x + 1) * 100, # p_high 80, # p_low 1000, # u_max 2000) # q_max ex.get_order(askers[x].current_order) # Process any messages in the book's queue while len(ex.book.message_queue) > 0: ex.book.process_messages() ex.book.pretty_book() # Hold the batch ex.hold_batch() print(ex.aggregate_demand, ex.aggregate_supply) # Graph the graph.graph_total_aggregates(1, 'r', 'b', 'g-') graph.graph_all_aggregates(2, 'r', 'b') print(ex.active_bids, ex.active_asks) # Send cancels for the odd orders for x in range(0, n): if x % 2 == 1: bidders[x].new_order('C', None, None, None, None) ex.get_order(bidders[x].current_order) # Create the N traders with asks and send to exchange for x in range(0, n): if x % 2 == 1: askers[x].new_order('C', None, None, None, None) ex.get_order(askers[x].current_order) # Process any messages in the book's queue while len(ex.book.message_queue) > 0: ex.book.process_messages() ex.book.pretty_book() # Hold the batch ex.hold_batch() print(ex.aggregate_demand, ex.aggregate_supply) # Confirm that those were the ones deleted graph.graph_total_aggregates(3, 'r', 'b', 'g-') graph.graph_all_aggregates(4, 'r', 'b') graph.display()
def doTrade(pool, stdPeriod, stdGuage1, stdGuage2, aft, af, as1t, as1, as2t, as2, bft, bf, bs1t, bs1, bs2t, bs2, cft, cf, cs1t, cs1, cs2t, cs2): global std, prices sname = str(stdPeriod) + '_' + str(stdGuage1) + '_' + str(stdGuage2) sname += '_' + aft + '_' + str(af) + '_' + as1t + '_' + str( as1) + '_' + as2t + '_' + str(as2) sname += '_' + bft + '_' + str(bf) + '_' + bs1t + '_' + str( bs1) + '_' + bs2t + '_' + str(bs2) sname += '_' + cft + '_' + str(cf) + '_' + cs1t + '_' + str( cs1) + '_' + cs2t + '_' + str(cs2) afma, as1ma, as2ma = getMas(aft, af), getMas(as1t, as1), getMas(as2t, as2) bfma, bs1ma, bs2ma = getMas(bft, bf), getMas(bs1t, bs1), getMas(bs2t, bs2) cfma, cs1ma, cs2ma = getMas(cft, cf), getMas(cs1t, cs1), getMas(cs2t, cs2) front = max(as1, as2, bs1, bs2, cs1, cs2) t = Trader(sname) t.args = [ aft, af, as1t, as1, as2t, as2, bft, bf, bs1t, bs1, bs2t, bs2, cft, cf, cs1t, cs1, cs2t, cs2 ] for i in range(front, len(prices)): price = prices[i] if std[stdPeriod][i] > stdGuage2: t.switchActiveCounter(2, price['dt'], price['rmb']) elif std[stdPeriod][i] > stdGuage1: t.switchActiveCounter(1, price['dt'], price['rmb']) else: t.switchActiveCounter(3, price['dt'], price['rmb']) for cntNo in range(3): if cntNo == 0: fma, s1, s1ma, s2, s2ma = afma, as1, as1ma, as2, as2ma if cntNo == 1: fma, s1, s1ma, s2, s2ma = bfma, bs1, bs1ma, bs2, bs2ma if cntNo == 2: fma, s1, s1ma, s2, s2ma = cfma, cs1, cs1ma, cs2, cs2ma if s1 == 0 and s2 == 0: continue volume = 0 notes = '' if s1 > 0 and fma[i - 1] <= s1ma[i - 1] and fma[i] > s1ma[i]: notes += 'f>s1;' + str(fma[i - 1]) + ';' + str( s1ma[i - 1]) + ';' + str(fma[i]) + ';' + str(s1ma[i]) + ';' volume += 1 if s1 > 0 and fma[i - 1] >= s1ma[i - 1] and fma[i] < s1ma[i]: notes += 'f<s1;' + str(fma[i - 1]) + ';' + str( s1ma[i - 1]) + ';' + str(fma[i]) + ';' + str(s1ma[i]) + ';' volume -= 1 if s2 > 0 and fma[i - 1] <= s2ma[i - 1] and fma[i] > s2ma[i]: notes += 'f>s2;' + str(fma[i - 1]) + ';' + str( s2ma[i - 1]) + ';' + str(fma[i]) + ';' + str(s2ma[i]) + ';' volume += 1 if s2 > 0 and fma[i - 1] >= s2ma[i - 1] and fma[i] < s2ma[i]: notes += 'f<s2;' + str(fma[i - 1]) + ';' + str( s2ma[i - 1]) + ';' + str(fma[i]) + ';' + str(s2ma[i]) + ';' volume -= 1 t.processOrder(price['dt'], price['rmb'], volume, cntNo=cntNo, notes=notes) pool.estimate(t) return t
idx = 0 first = True data: pd.DataFrame = feather.read_feather(data_path).iloc[:-45000] highestFit = float('-inf') #[float('-inf') for i in range(len(HIDDEN_LAYERS))] generationCount = 0 #[0 for i in range(len(HIDDEN_LAYERS))] print("Generating traders") bestTrader = None #[None for i in range(len(HIDDEN_LAYERS))] previousTraders: list[Trader] = [] while generationCount <= AMOUNTOFGENS: totalFitness = 0 new = False allTraders: list[Trader] = [] if first: base_trader = Trader(idx, MUTATION_RATE, SYMBOL, HIDDEN_LAYERS[0]) for i in range(len(HIDDEN_LAYERS)): layer = HIDDEN_LAYERS[i] traders: list[Trader] = [] for j in range(POPULATION_SIZE): print(f'Generating trader {idx}') if first: if idx == 0: traders.append(base_trader) else: if base_trader.brain.model_loaded: traders.append(base_trader.clone_mutate(idx)) else: traders.append(Trader(idx, MUTATION_RATE, SYMBOL, layer)) else:
if __name__ == '__main__': atexit.register(cleanup) logger = init_logger(__file__, 'info', email = False) logger.info('pyntrader.py began execution') conn = pymongo.Connection() data = conn.intrade intrade = intrade_api.Intrade() groups, contract_ids = {}, set() for rec in data.contract_groups.find({'trade': True}): groups[str(rec['_id'])] = [int(contract['id']) for contract in rec['contracts']] [contract_ids.add(int(contract['id'])) for contract in rec['contracts']] # override for testing environment groups = {'fake_id': [320111, 320112]} contract_ids = [320111, 320112] # on init, gets current balance, positions, and outstanding trades trader = Trader(data, intrade, contract_ids, logger) main()
def findHighAndLow(phighs, plows, start, pos): for j in range(start, pos + 1): if phighs[j] > high: high, hignIndex = phighs[j], j if plows[j] < low: low, lowIndex = plows[j], j if hignIndex != start and hignIndex != pos: high found elif hignIndex == pos: findHighAndLow(phighs, plows, lowindex - 1, lowindex) elif hignIndex == start: findHighAndLow(phighs, plows, start - 1, pos) if nearLowIndex != start and nearLowIndex != pos: low found if nearHignIndex == pos and nearLowIndex == start: findHighAndLow(phighs, plows, span + 1, pos) elif nearHignIndex == pos nearHigh = -9999999 nearLow = 9999999 nearHignIndex = nearLowIndex = 0 for j in range(i - near + 1, i + 1): if phighs[j] > nearHigh: nearHigh, nearHignIndex = phighs[j], j if plows[j] < nearLow: nearLow, nearLowIndex = plows[j], j farHigh = -9999999 farLow = 9999999 farHignIndex = farLowIndex = 0 for j in range(i - far + 1, i + 1): if phighs[j] > farHigh: farHigh, farHignIndex = phighs[j], j if plows[j] < farLow: farLow, farLowIndex = plows[j], j highGauge = lowGauge = 0 if nearHignIndex != farHignIndex: highGauge = nearHigh - (farHigh - nearHigh) * (i - nearHignIndex) / (farHignIndex - nearHignIndex) if plows[i] > highGauge: direct if nearHignIndex == farHignIndex: lowGauge = nearLow - (farLow - nearLow) * (i - nearLowIndex) / (farLowIndex - nearLowIndex) if for j in range(i - slowing + 1, i + 1): nearHigh = max(phighs[i-near+1 : i+1]) nearLow = min(plows[i-near+1 : i+1]) farHigh = max(phighs[i-far+1 : i+1]) farLow = min(plows[i-far+1 : i+1]) if pdiff = map(lambda f,s: f - s, phighs, plows) t = Trader(sname) direct = odirect = 0 for i in range(front, len(prices)): price = prices[i] diffavg = np.mean(pdiff[i-ssp : i+1]) highest = max(phighs[i-ssp+1 : i+1]) lowest = min(plows[i-ssp+1 : i+1]) smin = lowest + (highest - lowest) * risk / 100 smax = highest - (highest - lowest) * risk / 100 if ps[i] < smin: direct = -1 elif ps[i] > smax: direct = 1 volume = 0 if odirect == -1 and direct == 1: volume = 1 elif odirect == 1 and direct == -1: volume = -1 odirect = direct t.processOrder(price['dt'], price['rmb'], volume * 1000, cntNo=0, notes='') pool.estimate(t) return
response = None stop_order_response = [] take_profit_order_response = [] ohlcv_candles = [] order_counter = 0 msg = '' flag = False sc = SlackClient(SLACK_TOKEN) client = bitmex.bitmex(test=False, api_key=ID, api_secret=SECRET) strategy = Strategy(client, timeframe=TIMEFRAME) trader = Trader(client, sc, strategy, ohlcv_candles, money_to_trade=AMOUNT_MONEY_TO_TRADE, leverage=LEVERAGE) while True: if round(time.time()) % time_to_wait_new_trade[TIMEFRAME] == 0: time.sleep(1) response = trader.execute_trade() if response is not None: if trader.send_notifcation(response) is True: print('Notification send successfully') else: print('Notification Failed') exec_price = response[0]['price'] order_counter = order_counter + 1. print('Order Number : {}'.format(order_counter))