def handle_cmd(comment): try: username = comment.author.name cmd = comment.body.replace("u/crypto-trader-bot", "").replace('/', '').strip().upper() t = trader(username, db.db.traders_db) if(cmd.startswith('!JOIN')): t = trader(comment.author.name, db.db.traders_db) print("{} wants to join the fun!".format(comment.author.name)) comment.reply("You have been added! Use !CHECK to see your assets.") return elif(cmd.startswith('!CHECK')): try: username = cmd.split(' ')[1] except Exception as e: username = comment.author.name msg = checkBalance(username) comment.reply(msg) return else: action, amount, currency = cmd.split(' ') print("{} wants to {} {} {}.".format(username, action, amount, currency)) action = action.upper() currency = currency.upper() if("!BUY" == action): p = api.getPrice(currency) if (-1 == p): comment.reply("Error: You want to buy what?") return if('!' == amount): amount = float(t.assets['BTC'])/p else: amount = float(amount) r = t.buy(currency, amount, p) if (-1 == r): comment.reply("Error: Insufficient funds.") else: comment.reply("Success: Bought {} {} at {} BTC/{}".format(amount, currency, p, currency)) elif("!SELL" == action): p = api.getPrice(currency) if('!' == amount): amount = float(t.assets[currency])-0.00000001 else: amount = float(amount) if (-1 == p): comment.reply("Error: You want to buy what? Only ") return r = t.sell(currency, amount, p) if(-1 == r): comment.reply("Error: Insufficient funds") else: comment.reply("Success: Sold {} {} at {} BTC/{}".format(amount, currency, p, currency)) except Exception as e: print("Failed to handle cmd") print(e)
def __init__(self, target_num=10): ''' 当日全部股票 ''' self.trader = trader() holding_stocks = self.trader.holding.keys() self.sell_out([i for i in holding_stocks if i not in target_stocks]) self.sell_out([i for i in holding_stocks if i not in target_stocks], first=False)
def trading_system(subscribe_symbol, system_name, database, exchange_name, book_port, order_port, exchange_data_port, exchange_order_port, robot_trader_style, robot_trader_strategy, is_robot_trader,trade_interval,debug): print("\nNOTICE: To modify or cancel order, you have to remember order number submitted!") print(" Submit an order and remember its order number!\n") if not debug: print("NOTICE: No debug messages printed to screen, see it at LOGS folder if needed.. ") # launch getawayIn, must be paralell with bookbuilder p1 = Process(target=launch_getawayIn,args=(system_name,book_port,exchange_name,exchange_data_port,subscribe_symbol,debug,)) p1.start() # to synchronize bookbuilder and getawayIN... otherwise bookbuilder # start before getawayIn time.sleep(2) # launch bookbuilder with a new process p2 = Process(target=launch_bookbuilder,args=(system_name,database,book_port,exchange_name,debug)) p2.start() # to synchronize bookbuilder and getawayIN... otherwise bookbuilder # start before getawayIn time.sleep(2) # launch getawayOut with a new process p3 = Process(target=launch_getawayOut,args=(system_name,database,order_port,exchange_name,exchange_order_port,debug)) p3.start() # to synchronize bookbuilder and getawayIN... otherwise bookbuilder # start before getawayIn time.sleep(2) # launch trader and market data viewer trader1=trader(trade_interval,database,order_port,system_name,robot_trader_style,robot_trader_strategy,is_robot_trader,debug) trader1.market_price_viewer(subscribe_symbol)
def launch_trader(database, order_port, system_name, robot_trader_style, robot_trader_strategy, is_robot_trader, subscribe_symbol, trade_interval, debug): # launch trader and market data viewer trader1 = trader(trade_interval, database, order_port, system_name, robot_trader_style, robot_trader_strategy, is_robot_trader, debug) trader1.market_price_viewer(subscribe_symbol)
def __init__(self): t = trader() # 总资金 self.portfolio_value = t.balance.get('asset_balance') # 可用资金 self.available_cash = t.balance.get('enable_balance') self.positions_value = t.balance.get('market_value') self.positions = self.Positions(t.holding)
def buy_in(self, stock, first=True): ''' 开仓 ''' # 重新获取交易信息 print 'OSAKA SUCCESS: %s' % stock self.trader = trader() self.trader.buy(stock, 99) self.quit = True
def adjust(self): bag = get_osaka_stocks() target_stock = self.target_stock_decision(bag) holding_stocks = self.trader.holding.keys() # 清仓 if len(holding_stocks) == 2: self.sell_out(holding_stocks) self.trader = trader() # 开仓 if target_stock: self.buy_in(target_stock)
def adjust(self): bag = get_osaka_stocks() target_stock = self.target_stock_decision(bag) holding_stocks = self.trader.holding.keys() # 清仓 if len(holding_stocks)==2: self.sell_out(holding_stocks) self.trader = trader() # 开仓 if target_stock: self.buy_in(target_stock)
def sell_out(self, stocks, first=True): ''' 清仓 first 针对雪球1%无法清仓的情况对应处理 ''' if not first: # 重新获取交易信息 self.trader = trader() for stock in stocks: amount = self.trader.holding.get(stock).get('enable_amount') or 0 if not first or (first and amount > 100): current_price = float(self.stocks_info.get(stock).get('now')) trade_price = float(current_price) - 0.01 self.trader.sell(stock, amount, current_price)
def checkBalance(username): t = trader(username, db.db.traders_db) value = 0 msg = "Breakdown of assets for **{}**\n\n".format(username) for asset in t.assets.items(): msg += "* {} {}\n\n".format(asset[0], asset[1]) p = api.getPrice(asset[0]) if(-1 == p): continue value +=p*asset[1] value += t.assets['BTC'] value = round(value, 8) msg += "*Worth a total of {} BTC ".format(value) msg += time.strftime("on %a, %d %b %Y %H:%M:%S +0000*", time.gmtime()) return msg
def buy_in(self, stocks, first=True): ''' 开仓 first 针对剩余金额全部购买一支标的进行处理 ''' if not first: # 重新获取交易信息 self.trader = trader() # 账户可用余额 enable_balance = self.trader.enable_balance #print self.trader.balance for stock in stocks: current_price = float(self.stocks_info.get(stock).get('now')) amount = int(enable_balance/self.target_num/current_price/100) * 100 if first else\ int(enable_balance/current_price/100) * 100 if amount >= 100: self.trader.buy(stock, amount, current_price)
def buy_in(self, stocks, first=True): ''' 开仓 first 针对剩余金额全部购买一支标的进行处理 ''' if not first: # 重新获取交易信息 self.trader = trader() # 账户可用余额 enable_balance = self.trader.enable_balance #print self.trader.balance for stock in stocks: current_price = float(self.stocks_info.get(stock).get('now')) amount = int(enable_balance/self.target_num/current_price/100) * 100 if first else\ int(enable_balance/current_price/100) * 100 if amount>=100: self.trader.buy(stock, amount, current_price)
def test_trader(asset): monitor = trader() products = [] for product in monitor.client.get_products(): if "USD" in product["id"]: ticker = monitor.get_ticker(product["id"]) try: products.append({product["id"]: float(ticker["ask"])}) except KeyError as e: print(e) print(ticker["message"]) message = "Current GDAX USD exchange rates:" for product in products: for key in product: message += "\n{} {}".format(key, product[key]) print(monitor.get_macd("BTC-USD")) monitor.message_bot.send_message(message)
def __init__(self, arg): self.arg = arg self.simMode = arg.get('simMode', 1) self.config = arg.get('config', None) self.plot = arg.get('plot', None) self.fee1 = 1.002 self.fee2 = 1.0024 self.moveAmount = 8.0 self.moveStep = 2.0 self.moveAmountPosition = 0 self.log = logging.getLogger('manager') self.loadTradeModel() self.isCurrentActionDone = True self.currentDecision = {} self.trader = trader.trader(arg) self.initStrategy()
def __init__(self, arg): self.arg = arg self.simMode = arg.get('simMode', 1) self.config = arg.get('config', None) self.plot = arg.get('plot', None) self.fee1 = 1.002 self.fee2 = 1.0024 self.moveAmount = 7.0 self.moveStep = 2.0 self.moveAmountPosition = 0 self.log = logging.getLogger('manager') self.loadTradeModel() self.isCurrentActionDone = True self.currentDecision = {} self.trader = trader.trader(arg) self.initStrategy()
def assetSms(cache=False): last_info = '' info = '' message = '' # 读取昨日数据,存放于data.csv with open('data.csv') as f: last_info, info = f.readlines()[-2:] # 读取配置信息 user, passwd, a_reciever, a_portion = analysis_json(SMS_CONFIG) recievers = a_reciever.split(',') portions = a_portion.split(',') assert len(recievers) == len(portions) if not cache: # 不读取cache,则app上获取份额 sum_portions = sum([float(i) for i in portions]) asset = trader().get_message(sum_portions) last_info = info else: asset = info.split(',')[1] # 昨日净值 [date, last_asset] = last_info.split(',') if ',' in last_info else ['', ''] # 拼接短信内容 if date and last_asset: up_rate = (float(asset) - float(last_asset))/float(last_asset) * 100 message += u'<html><body><h3>%s 日净值<html><body><h3> %.4f' % (time.strftime('%Y-%m-%d'), float(asset)) message += u',涨 +%.2f%%</h3><br><h3>' % up_rate if up_rate > 0 else u',跌 %.2f%%</h3><br><h3>' % up_rate for num, reciever in enumerate(recievers): send_message = message + u'您的账户总资产:%.2f </h3><br><p>' % (float(portions[num]) * float(asset)) send_message += u'【From StockFucker】 </p></html></body>' if '396539169' not in reciever: sendMail(user, passwd, reciever, send_message) elif '396539169' in reciever and datetime.now().weekday() == 4: sendMail(user, passwd, reciever, send_message) time.sleep(60)
def run(self): startTime = datetime.now() #logger = logger(api) #api = api('EX5MTSTX-A816DXWK-UUDB68A5-BBGMQ2B5-1O144CWS','08caaaf52a9a83512a8b56323b628a293d173ce4565dceb645524b6c0542ecdb') print "3) get rates" self.api.getRates() print "4) create currencies" cutoff = 5 print "5) get search" newSearch = search(self.api) print "6) solve search" searchTree = newSearch.findSolution(random.choice(self.currencies)) print "total calculation time: %s" % ((datetime.now() - startTime).total_seconds()) if searchTree[1][0] != "ltc": print "NOT LTC" time.sleep(0.5) return """if searchTree[2] <= 1.0: print "non-positive trade" time.sleep(0.5) return""" print "7) get user count" userCount = 1.0#self.user.getCurrency(searchTree[1][0]) if not userCount: print "could not trade due to insufficient funds" sys.exit(0) print "using %s of %s" % (userCount, searchTree[1][0]) #search.solveTree(searchTree[0]) print "8) get trader" newTrader = trader(self.api, searchTree[1], searchTree[2]) print "9) execute trader" traderResult = newTrader.executeChain(newTrader.chain, userCount) endTime = datetime.now() differenceTime = (endTime - startTime).total_seconds() print "10) write to logger" self.logger.write(traderResult, searchTree[1][0], searchTree[2], searchTree[1], differenceTime, datetime.now()) print "final result: ", traderResult print "##3) get rates" self.api.getRates() print "##4) create currencies" cutoff = 5 print "##5) get search" newSearch = search(self.api) print "##6) solve search" searchTree = newSearch.findSolution(random.choice(self.currencies))
def __init__(self, target_num=10): ''' 当日全部股票 ''' self.stocks_info = select(read_cache=False) self.target_num = target_num self.trader = trader()
class market: #marketwatch dt = 1 / 252 clock = watch(dt) #we setup a market periodOfTrade = 10 marketMaker = marketMaker(clock) marketMaker.randomGenerator(size=int(periodOfTrade / dt), numberOfAssets=2) print(marketMaker.dzMatrix.shape) autoCorr = np.matrix([[0.4], [0.5]]) crossSecCorr = np.matrix([[1, 0.6], [0.6, 1]]) marketMaker.setCorr(autoCorr, crossSecCorr) AAPL = marketMaker.IPO(0, 'AAPL', 132.60, 1000000000, 1.2, 1.5, 0.38) JNJ = marketMaker.IPO(1, 'JNJ', 163.52, 1000000000, 1.32, 1.9, 0.42) valueTrader123 = trader('valueTrader', 63, 1, 500000000, marketMaker, clock) trendFollower = trader('trendFollower', 30, 1, 500000000, marketMaker, clock) passiveTrader = trader('passiveTrader', 63, 1, 500000000, marketMaker, clock) noiseTrader = trader('noiseTrader', 1, 1, 500000000, marketMaker, clock) Traders = [valueTrader123, trendFollower, passiveTrader, noiseTrader] marketMaker.setRiskFreeRate(0.02) #we generate market activity if __name__ == '__main__': clock.start() while clock.time() <= periodOfTrade: #years qoutes = marketMaker.sendQoutes() Orders = 0 for trader in Traders: trader.receiveQoutes(qoutes, clock.time()) Orders += trader.respond() marketMaker.receiveOrders(Orders) clock.tick() output = marketMaker.stockPrice def returns(output1, Asset): returns = [] for i in range(1, len(output1[Asset]) - 1): a = (output1[Asset][i + 1] / output1[Asset][i]) returns.append(np.log(a)) return returns #Output print(output) plt.style.use('seaborn') figure, axis = plt.subplots(2, 1) axis[0].plot(output['JNJ'], label='JNJ') axis[0].set_ylabel('Price, ($)') axis[0].legend(loc='upper left') axis[0].plot(output['AAPL'], label='AAPL') axis[0].set_ylabel('Price, ($)') axis[0].legend(loc='upper left') axis[1].scatter(returns(output, 'AAPL'), returns(output, 'JNJ')) axis[1].set_ylabel('JNJ') axis[1].set_xlabel('AAPL') axis[1].legend(loc='upper left') plt.show()
def __init__(self, use_pool=True): self.quit = False self.trader = trader() self.use_pool = use_pool
*if you dont use amount or quantity minimum quantity will be used *for Trade you can add multiple targets separating them with comma ''' ### Get admin chat_id from config file ### For more security replies only send to admin chat_id adminCID = config.telegram_admin_chatID ### Enable logging logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO) logger = logging.getLogger(__name__) trader_class = trader() ### This function run command and send output to user def runCMD(bot, update): if not isAdmin(bot, update): return try: usercommand = update.message.text usercommand = usercommand.split() options = defaultdict() response = "" for i in range(1, len(usercommand), 2): if (usercommand[i][2:] == "takeProfitPrice_list"): options[usercommand[i][2:]] = usercommand[i + 1].split(",") else: