示例#1
0
    def test_get_sell_amount(self):
        session = mommy.make(Session)
        trader = Trader(session_id=session.id)

        amount = trader.get_sell_amount()

        assert amount == 59408221
示例#2
0
    def test_get_buy_amount(self):
        session = mommy.make(Session)
        trader = Trader(session_id=session.id)

        amount = trader.get_buy_amount(7500)

        assert amount == 1333333333333
示例#3
0
    def execute(self, job):
        t = Trader(job.conf['trader'])
        d = t.balance()
        for b in d:
            for (k, v) in b.items():
                print(k + ':' + str(v)).encode('utf-8')

        return 0
示例#4
0
def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument("api_key")
    args = parser.parse_args()
    api_key = args.api_key

    trader = Trader(api_key, "aapl")

    trader.train()
示例#5
0
    def __init__(self, config):
        # Assign random session ID for logs, etc
        self.session_id = str(uuid.uuid4())

        self.config = config
        self.log_file = open("logs/" + self.session_id + ".txt", "w")
        self.logger = Logger(self.message_queue)

        self.scraper = DataInput(self.article_queue, self.logger, self.config)
        self.processes.append(Process(target=self.scraper.run))
        for num in range(config["data_analysis"]["num_workers"]):
            obj = DataAnalysis(self.config, self.logger, self.article_queue,
                               self.result_queue)
            self.processes.append(Process(target=obj.run))
        self.trader = Trader(self.result_queue, self.logger, self.config)
        self.processes.append(Process(target=self.trader.run))

        self.gui = tk.Tk()
        self.gui.geometry("1080x720")

        tk.Tk.wm_title(self.gui, "Algo Trading Bot")

        container = tk.Frame(self.gui)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        menu = tk.Menu(container)
        viewmenu = tk.Menu(menu, tearoff=0)
        menu.add_cascade(label="View", menu=viewmenu)
        viewmenu.add_command(label="Control",
                             command=lambda: self.show_frame(MainPage))
        viewmenu.add_command(label="Stats",
                             command=lambda: self.show_frame(StatsPage))
        tk.Tk.config(self.gui, menu=menu)

        self.frames = {}

        for frameType in (MainPage, StatsPage):
            frame = frameType(container, self)
            self.frames[frameType] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(MainPage)

        self.gui.after(10, self.poll_messages)
        self.gui.after(10, self.prune_databases)
        self.gui.after(10, self.sell_positions)
        self.gui.after(10, self.check_processes)
        self.gui.after(1, self.start)

        while True:
            try:
                self.gui.mainloop()
            except UnicodeDecodeError:
                pass
示例#6
0
 def __init__(self, **kwargs):
     try:
         Trader.__init__(self, **kwargs)
         self.account = Bittrex(kwargs.get('api_key'),
                                kwargs.get('api_secret'))
         self._exchange = 'BITTREX'
         self.streamer = HandleSocket()
         self.streamer.authenticate(kwargs.get('api_key'),
                                    kwargs.get('api_secret'))
         self.active_symbols = [
         ]  #list of symbols that are currently trading {'symbol': 'BTC-USDT', 'buy_price':xxx, 'order_id': xxx, 'latest_price': xxx}
         logger.info('Bittrex trader successfully booted')
         self.streamer.trader = self
     except Exception as e:
         logger.exception(e)
示例#7
0
    def execute(self, job):
        t = Trader.get_instance(job['trader'])

        entrusts = t.check_available_cancels()
        entrust_to_cancle = []
        for invest in job.result[:]:
            for e in entrusts:
                if e.iotype == 'sell' and e.stock_code == invest.code:
                    if e.entrust_price == invest.price:
                        job.result.remove(invest)
                    else:
                        entrust_to_cancle.append(e.entrust_no)

        if len(entrust_to_cancle):
            ret = t.cancel_entrusts(','.join(entrust_to_cancle))
            job.notice(str(ret))
            job.trade(str(ret))
            #不要过于频繁操作
            time.sleep(1)

        position = t.position()
        for i, v in enumerate(job.result):
            #找到该股的持仓数据
            v_position = ''
            for p in position:
                if p.stock_code == v.code:
                    v_position = p
            #没有持仓
            if v_position == '':
                continue

            #设置卖出参数
            job.result[i].amount = v_position.enable_amount

        return 0
示例#8
0
    def execute(self, job):
        t = Trader.get_instance(job['trader'])

        entrusts = t.check_available_cancels()
        entrust_to_cancle = []
        for invest in job.result[:]:
            for e in entrusts:
                if e.iotype == 'buy' and e.stock_code == invest.code:
                    if e.entrust_price == invest.price:
                        job.result.remove(invest)
                    else:
                        entrust_to_cancle.append(e.entrust_no)

        if len(entrust_to_cancle):
            ret = t.cancel_entrusts(','.join(entrust_to_cancle))
            job.notice(str(ret))
            job.trade(str(ret))
            #不要过于频繁操作
            time.sleep(1)

        for invest in job.result:
            if invest.amount == 0:
                continue
            ret = t.buy(invest.code, invest.price, invest.amount)
            job.notice(str(ret))
            job.trade(str(ret))
            #不要过于频繁操作
            time.sleep(1)

        return 0
示例#9
0
    def test_get_sell_max_value(self):
        session = mommy.make(Session)
        trader = Trader(session_id=session.id)

        settings.EXCHANGES['BL3P']['max_sell_value'] = {
            'LTCEUR': 1,
            'BTCEUR': 1
        }

        amount = trader.get_sell_amount()

        settings.EXCHANGES['BL3P']['max_sell_value'] = {
            'LTCEUR': -1,
            'BTCEUR': -1
        }

        assert amount == 1
示例#10
0
    def test_get_buy_min_value(self):
        session = mommy.make(Session)
        trader = Trader(session_id=session.id)

        settings.EXCHANGES['BL3P']['min_buy_value'] = {
            'BTCEUR': 10000000,
            'LTCEUR': 10000000
        }

        amount = trader.get_buy_amount(100000000)

        settings.EXCHANGES['BL3P']['max_buy_value'] = {
            'BTCEUR': 10000000,
            'LTCEUR': 5000000
        }

        assert amount == 100000000
示例#11
0
class TraderSimulation:

    def __init__(self, data, predictions, config, initial_balance=1000, fee=0.001, uncertainty=0):
        self.data = data
        predictor = SimulatedPredictor(predictions, data, uncertainty)
        wallet = SimulatedWallet(initial_balance, fee)
        self.trader = Trader(config, wallet, predictor)

    def run(self):
        logging.info("Simulation Started")
        for i in range(0, self.data[list(self.data.keys())[0]].shape[0]):
            for coin in self.data.keys():
                self.trader.process_data(coin, self.data[coin].iloc[i])
                if i % 10000 == 0:
                    logging.info("Simulation Progress %f%%" % ((i/self.data[coin].shape[0])*100))

        logging.info("Simulation Ended")
        return self.trader.wallet.get_net_worth()
示例#12
0
    async def run_traders(self):
        account = await oanda.api.OandaApi().account(
            account_id=oanda.config.OANDA_ACCOUNT_ID)
        asyncio.ensure_future(self.listen_on_transactions(account))

        instruments = ["USD_PLN", "EUR_USD"]
        for trader in [
                Trader(account=account, instrument=instrument)
                for instrument in instruments
        ]:
            asyncio.ensure_future(trader.run_forever())
示例#13
0
    def execute(self, job):
        q = Quotation()
        hgt = q.get_hgt_capital()
        hgt_estimate = estimate_to_close(hgt)

        #沪港通指标
        buy = 0
        if hgt > self.HGT_LIM:
            buy = 1
        if get_exchange_time(
        ) > 30 * 60 and hgt_estimate > self.HGT_ESTIMATE_LIM:
            buy = 1

        if buy == 0:
            job.status = 0
            job.result.clear()
            return 0

        if buy == 1:
            job.status = 1

        t = Trader.get_instance(job['trader'])
        position = t.position()
        balance = t.balance()
        enable_balance = balance[0].enable_balance

        codes = []
        for i, v in enumerate(job.result):
            codes.append(v.code)
        quotes = q.get_realtime_quotes(codes)

        temp_result = copy.copy(job.result)
        job.result.clear()
        for i, v in enumerate(temp_result):
            #找到该股的持仓数据
            v_position = ''
            for p in position:
                if p.stock_code == v.code:
                    v_position = p
            #达到持仓上限
            if v_position != '' and v_position.current_amount >= v.amount:
                continue
            #设置买入参数
            v.price = quotes[v.code].buy
            if get_turnover_brokerage(v.price * v.amount) > enable_balance:
                continue
            enable_balance -= get_turnover_brokerage(v.price * v.amount)
            job.result.append(v)

        return 0
示例#14
0
    def execute(self, job):
        t = Trader.get_instance(job['trader'])
        balance = t.balance()
        enable_balance = balance[0].enable_balance

        q = Quotation()
        quote = q.get_realtime_quotes([self.GC001, self.R001])
        for (k,v) in quote.items():
            string = v.__str__()
            print string.encode('utf-8')

        if quote[self.GC001].buy > quote[self.R001].buy and enable_balance >= self.GC001_UNIT * self.HAND:
            amount=int(enable_balance/self.HAND/self.GC001_UNIT)*self.GC001_UNIT
            ret = t.sell(self.GC001, price=quote[self.GC001].buy, amount=int(enable_balance/self.HAND/self.GC001_UNIT)*self.GC001_UNIT)
            job.notice(str(ret))
            job.trade(str(ret))

        quote = q.get_realtime_quotes([self.GC001, self.R001])
        amount=int(enable_balance/self.HAND/self.R001_UNIT)*self.R001_UNIT
        ret = t.sell(self.R001, price=quote[self.R001].buy, amount=amount)

        job.notice(str(ret))
        job.trade(str(ret))


        #t = Trader.get_instance(job['trader'])
        #d = t.position()
        ##d = t.entrust()
        ##d = t.buy('601288', price=3.1, amount=100)
        ##d = t.sell('601288', price=3.5, amount=100)
        ##d = t.entrust()
        ##d = t.check_available_cancels()
        ##d = t.cancel_all_entrust()
        ##d = t.cancel_entrust('500', '601288')
        ##d = t.get_deal('2017-04-11')
        #job.notice(str(d))
        #job.trade(str(d))

        return 0
示例#15
0
def run():
    websocket.enableTrace(True)
    session = Session.objects.create(
        status=Session.RUNNING,
        ma1=settings.BOT_DATA_SAMPLE_MA1,
        ma2=settings.BOT_DATA_SAMPLE_MA2,
        ma3=settings.BOT_DATA_SAMPLE_MA3,
        data_range=settings.BOT_DATA_SAMPLE_RANGE,
        data_group=settings.BOT_DATA_SAMPLE_GROUP,
        data_interval=settings.BOT_TICKER_INTERVAL,
        pair=settings.BOT_DEFAULT_PAIR,
    )
    trader = Trader(session_id=session.id)
    session.start()

    logger.log('session', 'Session #{} created'.format(session.id))
    logger.log('start', 'Bot running')

    ws = Bl3pWebSocket(get_trades_path(session.pair),
                       on_message=on_message,
                       on_error=on_error)
    ws.session = session
    ws.trader = trader
    ws.run_forever()
示例#16
0
    def execute(self, job):
        t = Trader.get_instance(job['trader'])
        balance = t.balance()
        enable_balance = balance[0].enable_balance

        q = Quotation()
        quote = q.get_realtime_quotes([self.GC001, self.R001])
        #for (k,v) in quote.items():
        #    string = v.__str__()
        #    print string.encode('utf-8')

        #job.result.invest = []
        job.result.clear()
        if quote[self.GC001].buy > quote[self.R001].buy and enable_balance >= self.GC001_UNIT * self.HAND:
            amount=int(enable_balance/self.HAND/self.GC001_UNIT)*self.GC001_UNIT
            #invest = Invest({'name':'GC001', 'code':self.GC001, 'amount':amount, 'price':quote[self.GC001].buy})
            invest = {'name':'GC001', 'code':self.GC001, 'amount':amount, 'price':quote[self.GC001].buy}
            job.result.append(invest)
            enable_balance = enable_balance - amount * self.HAND

        quote = q.get_realtime_quotes([self.GC001, self.R001])
        amount=int(enable_balance/self.HAND/self.R001_UNIT)*self.R001_UNIT
        #invest = Invest({'name':'R001', 'code':self.R001, 'amount':amount, 'price':quote[self.R001].buy})
        invest = {'name':'R001', 'code':self.R001, 'amount':amount, 'price':quote[self.R001].buy}
        job.result.append(invest)


        #q = Quotation()
        #quote = q.get_realtime_quotes([self.GC001, self.R001])
        #for (k,v) in quote.items():
        #    string = v.__str__()
        #    print string.encode('utf-8')

        #if quote[self.GC001].buy > quote[self.R001].buy and enable_balance >= self.GC001_UNIT * self.HAND:
        #    amount=int(enable_balance/self.HAND/self.GC001_UNIT)*self.GC001_UNIT
        #    ret = t.sell(self.GC001, price=quote[self.GC001].buy, amount=int(enable_balance/self.HAND/self.GC001_UNIT)*self.GC001_UNIT)
        #    job.notice(str(ret))
        #    job.trade(str(ret))

        ##不要过于频繁操作
        #time.sleep(2)
        #balance = t.balance()
        #enable_balance = balance[0].enable_balance
        #quote = q.get_realtime_quotes([self.GC001, self.R001])
        #amount=int(enable_balance/self.HAND/self.R001_UNIT)*self.R001_UNIT
        #ret = t.sell(self.R001, price=quote[self.R001].buy, amount=amount)

        #job.notice(str(ret))
        #job.trade(str(ret))


        #t = Trader.get_instance(job['trader'])
        #d = t.position()
        ##d = t.entrust()
        ##d = t.buy('601288', price=3.1, amount=100)
        ##d = t.sell('601288', price=3.5, amount=100)
        ##d = t.entrust()
        ##d = t.check_available_cancels()
        ##d = t.cancel_all_entrust()
        ##d = t.cancel_entrust('500', '601288')
        ##d = t.get_deal('2017-04-11')
        #job.notice(str(d))
        #job.trade(str(d))

        return 0
示例#17
0
 def __init__(self, data, predictions, config, initial_balance=1000, fee=0.001, uncertainty=0):
     self.data = data
     predictor = SimulatedPredictor(predictions, data, uncertainty)
     wallet = SimulatedWallet(initial_balance, fee)
     self.trader = Trader(config, wallet, predictor)
    def execute(self, job):
        q = Quotation()
        hgt = q.get_hgt_capital()
        hgt_estimate = estimate_to_close(hgt)

        #沪港通指标
        sell = 0
        if hgt < self.HGT_LIM:
            sell = 1
        if get_exchange_time(
        ) > 30 * 60 and hgt_estimate < self.HGT_ESTIMATE_LIM:
            sell = 1
        if hgt < self.HGT_KEEP_LIM:
            sell = 2
        if get_exchange_time(
        ) > 30 * 60 and hgt_estimate < self.HGT_KEEP_ESTIMATE_LIM:
            sell = 2

        if sell == 0:
            job.status = 0
            job.result.clear()
            return 0

        if sell != 0:
            job.status = 1

        t = Trader.get_instance(job['trader'])
        position = t.position()

        codes = []
        for i, v in enumerate(job.result):
            codes.append(v.code)
        quotes = q.get_realtime_quotes(codes)

        temp_result = copy.copy(job.result)
        job.result.clear()
        for i, v in enumerate(temp_result):
            #找到该股的持仓数据
            v_position = ''
            for p in position:
                if p.stock_code == v.code:
                    v_position = p
            #没有持仓
            if v_position == '':
                continue
            #盈利卖出
            if sell == 1:
                v.price = max(
                    quotes[v.code].buy,
                    round(
                        v_position.keep_cost_price *
                        (1 + self.INCOME_RATION_LIM), 2))
            #保本卖出
            elif sell == 2:
                v.price = v_position.keep_cost_price

            #设置卖出参数
            v.amount = v_position.enable_amount
            job.result.append(v)

        return 0
示例#19
0
# @@Author: [email protected]
# @CreateDate: 2016-05-19 00:46
# @ModifyDate: 2016-05-19 00:46
# Copyright ? 2016 Baidu Incorporated. All rights reserved.
#***************************************************************#

import sys
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
from trader.trader import Trader
import utils.const as CT
import yaml

t = Trader('xq')

def my_job(conf):
    print conf
    global t
    #d = t.sell('131810', price=1, amount=20)
    d = t.balance()
    print d
    for b in d:
        for (k,v) in b.items():
            print (k + ':' + str(v)).encode('utf-8')

def add_job(sched):
    #sched.add_job(my_job, 'interval', seconds=5)
    #sched.add_job(my_job, 'cron', second='*/30', args = [CT.CONF_DIR + 'trader/ht.json'])
    #sched.add_job(my_job, 'cron', minute = 10, hour = 13, args = [CT.CONF_DIR + 'trader/ht.json'])
示例#20
0
def main():
    api_config = Path(os.path.join('.', 'API_key.json'))
    with api_config.open('rt') as handle:
        config = json.load(handle)
    global trader
    trader = Trader(config['api_key'], config['secret_key'], config['account_id'])
示例#21
0
    def test_balance(self):
        t = Trader.get_instance('yh')
        d = t.balance()

        self.assertEqual(d[0].status, 'ok')
        self.assertGreater(d[0].enable_balance, 0)
示例#22
0
class Bot:
    # Start pyvirtualdisplay for headless runs
    display = Display(visible=0, size=(800, 800))
    display.start()

    # Process variables
    scraper = None
    trader = None
    processes = []

    # Queues to be delegated to sub-processes
    message_queue = Queue()
    article_queue = Queue()
    result_queue = Queue()

    running = False

    # Initializes all of the processes
    def __init__(self, config):
        # Assign random session ID for logs, etc
        self.session_id = str(uuid.uuid4())

        self.config = config
        self.log_file = open("logs/" + self.session_id + ".txt", "w")
        self.logger = Logger(self.message_queue)

        self.scraper = DataInput(self.article_queue, self.logger, self.config)
        self.processes.append(Process(target=self.scraper.run))
        for num in range(config["data_analysis"]["num_workers"]):
            obj = DataAnalysis(self.config, self.logger, self.article_queue,
                               self.result_queue)
            self.processes.append(Process(target=obj.run))
        self.trader = Trader(self.result_queue, self.logger, self.config)
        self.processes.append(Process(target=self.trader.run))

        self.gui = tk.Tk()
        self.gui.geometry("1080x720")

        tk.Tk.wm_title(self.gui, "Algo Trading Bot")

        container = tk.Frame(self.gui)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        menu = tk.Menu(container)
        viewmenu = tk.Menu(menu, tearoff=0)
        menu.add_cascade(label="View", menu=viewmenu)
        viewmenu.add_command(label="Control",
                             command=lambda: self.show_frame(MainPage))
        viewmenu.add_command(label="Stats",
                             command=lambda: self.show_frame(StatsPage))
        tk.Tk.config(self.gui, menu=menu)

        self.frames = {}

        for frameType in (MainPage, StatsPage):
            frame = frameType(container, self)
            self.frames[frameType] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(MainPage)

        self.gui.after(10, self.poll_messages)
        self.gui.after(10, self.prune_databases)
        self.gui.after(10, self.sell_positions)
        self.gui.after(10, self.check_processes)
        self.gui.after(1, self.start)

        while True:
            try:
                self.gui.mainloop()
            except UnicodeDecodeError:
                pass

    def poll_messages(self):
        try:
            msg = self.message_queue.get(True)
            if msg is not None:
                self.print_to_screen(msg)
                print(msg)
                self.log_file.write(msg + "\n")
                self.log_file.flush()
                self.gui.after(100, self.poll_messages)
            else:
                self.gui.after(100, self.poll_messages)
        except Exception as e:
            self.logger.log("Main", "error",
                            "Error polling messages: " + str(e))

        self.gui.after(100, self.poll_messages)

    def prune_databases(self):
        try:
            self.logger.log("Main", "informative", "Triggering db prune...")
            self.scraper.prune_databases()
        except Exception as e:
            self.logger.log("Main", "error",
                            "Error pruning databases: " + str(e))

        self.gui.after(600000, self.prune_databases)  # Prune every 10 mins

    def sell_positions(self):
        try:
            self.logger.log("Main", "informative",
                            "Triggering position sell-off...")
            self.trader.sell_positions()
        except Exception as e:
            self.logger.log("Main", "error",
                            "Error selling positions: " + str(e))

        self.gui.after(600000, self.sell_positions)  # Sell every 10 mins

    def check_processes(self):
        try:
            self.logger.log("Main", "informative", "Checking processes...")
            for process in self.processes:
                proc = psutil.Process(process.pid)
                if not proc.is_running():
                    self.logger.log("Main", "error",
                                    "Process crashed!  Exiting program.")
                    self.stop(
                    )  # We can't trust the program after a process crashes.
            self.logger.log("Main", "informative", "Processes OK!")
        except Exception as e:
            self.logger.log("Main", "error",
                            "Error checking processes: " + str(e))
            self.stop(
            )  # Stop here sinc a process probably died, causing this error

        self.gui.after(100, self.check_processes)  # Check again in 100ms

    # Starts the processes
    def start(self):
        self.running = True
        self.print_to_screen('Starting bot...')

        for process in self.processes:
            process.start()

    # Shuts down the program
    def stop(self):
        self.running = False
        self.trader.quit()
        for process in self.processes:
            process.terminate()
        exit()

    def print_trade(self, str):
        self.frames[MainPage].print_trade(str)

    def print_to_screen(self, str):
        self.frames[MainPage].print(str)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()