def mainLoop(pair, period): global tgupdateid base, coin = pair.split('_') position_open = False position_size = False position_entry = False position_stopLoss = False expected_risk_persent = False expected_risk = False now = getCurrentTime() chart = getHeikinAshi(pair, period, now - period * 1000, now) log.debug('Last five candles:') for candle in chart[-5:]: log.debug(candle) lastCandleDate = chart[-1]['date'] log.debug( f'Current candle date: {lastCandleDate}, {datetime.datetime.utcfromtimestamp(lastCandleDate)}' ) if trade: currentCoinBalance = float(polo.returnBalances()[coin]) if currentCoinBalance: log.info( f'Found available balance of {currentCoinBalance} {coin}, calculating stop loss...' ) n = -1 while not position_stopLoss: lastCandleColor = chart[n - 1]['color'] candleBeforeColor = chart[n - 2]['color'] if candleBeforeColor != lastCandleColor: position_stopLoss = float(chart[n - 1]['low']) log.info(f'Stop loss set to {position_stopLoss}') # tg_message(f'Stop loss set to {position_stopLoss}') position_open = True log.debug(f'position_open: {position_open}') n -= 1 else: print('Check') currentPrice = api.getTicker(polo, pair) lastCandleColor = chart[-2]['color'] candleBeforeColor = chart[-3]['color'] if lastCandleColor == 'green' and candleBeforeColor == 'red': total_balance = api.getTotalBalance(polo) position_entry = chart[-2]['high'] position_stopLoss = chart[-2]['low'] if currentPrice < position_entry and currentPrice > position_stopLoss: candle_change = 1 - (chart[-2]['low'] / chart[-2]['high']) maxloss = total_balance * maxrisk available_balance = float(polo.returnBalances()[base]) position_size = min(maxloss / candle_change, available_balance) if maxposition: position_size = min(position_size, maxposition) expected_risk = position_size * candle_change expected_risk_persent = expected_risk / total_balance position_size = float(f'{position_size:.8f}') log.info(f'Candle risk: {candle_change * 100:.3f}%') log.info(f'Available balance: {available_balance} {base}') log.info(f'Position entry: {position_entry}') log.info(f'Position stop loss: {position_stopLoss}') log.info(f'Position size: {position_size} {base}') log.info( f'Expected risk: {expected_risk_persent*100:.2f}%, {expected_risk:.8f} {base}' ) # tg_message(f'''New position setup # Candle risk: {candle_change * 100:.3f}% # Available balance: {available_balance} {base} # Position entry: {position_entry} # Position stop loss: {position_stopLoss} # Position size: {position_size} {base} # Expected risk: {expected_risk_persent*100:.2f}%, {expected_risk:.8f} {base} # ''') while True: now = getCurrentTime() fromLastCandle = now % period untilNextCandle = period - fromLastCandle log.info( f'Waiting {datetime.datetime.utcfromtimestamp(untilNextCandle).strftime("%H:%M:%S")} until new candle...' ) nextCandleTime = chart[-1]['date'] + period log.debug(f'Next candle date: {nextCandleTime}') # Tick check while getCurrentTime() < nextCandleTime: if commands: tgupdateid = tg_handleUpdates(tgupdateid) if trade: currentPrice = api.getTicker(polo, pair) if position_entry and currentPrice > position_entry: log.info( f'Entry price of {position_entry} hit, buying {coin}...' ) coinBefore = float(polo.returnBalances()[coin]) baseBefore = float(polo.returnBalances()[base]) result = api.buy(polo, pair, market=True, total=position_size) log.debug(result) coinAfter = float(polo.returnBalances()[coin]) baseAfter = float(polo.returnBalances()[base]) coinAmount = f'{coinAfter - coinBefore:.8f}' baseAmount = f'{baseBefore - baseAfter:.8f}' log.info( f'Bought {coinAmount} {coin} for {baseAmount} {base} at {currentPrice}' ) tg_message(f'''Entry price hit {pair} Buy Rate: {currentPrice} Amount: {coinAmount} {coin} Total:{baseAmount} {base}''') position_open = True log.debug(f'position_open: {position_open}') position_entry = False log.debug('Position entry removed') if position_open and currentPrice < position_stopLoss: log.info( f'Stop loss of {position_stopLoss} hit, selling {coin}...' ) coinBefore = float(polo.returnBalances()[coin]) baseBefore = float(polo.returnBalances()[base]) result = api.sell(polo, pair, market=True, all=True) log.debug(result) coinAfter = float(polo.returnBalances()[coin]) baseAfter = float(polo.returnBalances()[base]) coinAmount = f'{coinBefore - coinAfter:.8f}' baseAmount = f'{baseAfter - baseBefore:.8f}' log.info( f'Sold {coinAmount} {coin} for {baseAmount} {base} at {currentPrice}' ) tg_message(f'''Stop loss hit {pair} Sell Rate: {currentPrice} Amount: {coinAmount} {coin} Total: {baseAmount} {base}''') position_stopLoss = False log.debug('Position stop loss removed') position_entry = False log.debug('Position entry removed') position_open = False log.debug(f'Position open: {position_open}') if position_stopLoss and not position_open and currentPrice < position_stopLoss: log.info('Entry not hit, position cancelled') # tg_message('Entry not hit, position cancelled') position_stopLoss = False log.debug('Position stop loss removed') position_entry = False log.debug('Position entry removed') position_open = False log.debug(f'position_open: {position_open}') time.sleep(tick) lastCandleDate = chart[-1]['date'] log.info('Getting new candle...') chart = getHeikinAshi(pair, period, now - period * 1000, now, chart[-1]['date']) lastCandleColor = chart[-2]['color'] candleBeforeColor = chart[-3]['color'] log.debug(chart[-3]) log.debug(chart[-2]) log.debug(chart[-1]) log.info( f'Candle pattern is {candleBeforeColor} = > {lastCandleColor}') if lastCandleColor == 'green' and candleBeforeColor == 'red': log.info('Time to buy') if private_api: total_balance = api.getTotalBalance(polo) available_balance = float(polo.returnBalances()[base]) if available_balance > 2: position_entry = chart[-2]['high'] position_stopLoss = chart[-2]['low'] candle_change = 1 - (chart[-2]['low'] / chart[-2]['high']) maxloss = total_balance * maxrisk position_size = min(maxloss / candle_change, available_balance) if maxposition: position_size = min(position_size, maxposition) expected_risk = position_size * candle_change expected_risk_persent = expected_risk / total_balance position_size = float(f'{position_size:.8f}') log.info(f'Candle risk: {candle_change * 100:.3f}%') log.info(f'Available balance: {available_balance} {base}') log.info(f'Position entry: {position_entry}') log.info(f'Position stop loss: {position_stopLoss}') log.info(f'Position size: {position_size} {base}') log.info( f'Expected risk: {expected_risk_persent*100:.2f}%, {expected_risk:.8f} {base}' ) # tg_message(f'''New position setup # Candle risk: {candle_change * 100:.3f}% # Available balance: {available_balance} {base} # Position entry: {position_entry} # Position stop loss: {position_stopLoss} # Position size: {position_size} {base} # Expected risk: {expected_risk_persent*100:.2f}%, {expected_risk:.8f} {base} # ''') if call: log.info('Calling {tg_username}...') tg_call(tg_username, f'Time to buy {pair}') elif lastCandleColor == 'red' and candleBeforeColor == 'green': log.info('Time to move stop loss') if private_api and position_open: position_stopLoss = chart[-2]['low'] log.info(f'Position stop loss moved to {position_stopLoss}') # tg_message(f'Position stop loss moved to {position_stopLoss}') if call: log.info('Calling {tg_username}...') tg_call(tg_username, f'Move stop loss on {pair}') elif lastCandleColor == 'red' and position_open: position_stopLoss = chart[-2]['low'] log.info(f'Position stop loss moved to {position_stopLoss}') # tg_message(f'Position stop loss moved to {position_stopLoss}') else: log.info('Nothing to do...')
def update(withPolicy=None): global balance, SIM, max_spend_rolling token_change = False # run regularly on minute-by-minute interval sell_matrix = [] buy_matrix = [] stringOfStocks = ','.join(symb) quotes = [] if not SIM: quotes = get_quotes(symbol=stringOfStocks, premarket=False) for e in range(len(symb)): if not SIM: obj = update_vals(symb[e], quotes[e]) else: obj = update_vals(symb[e], sim.get_quotes(symb[e])) if obj is None: continue defPolicy = withPolicy # check if optimal policy exists, otherwise use default if not REF and ("policy" in db[symb[e]] and db[symb[e]]["policy"] is not None): defPolicy = db[symb[e]]["policy"] elif defPolicy is None: #defPolicy must be populated defPolicy = defaultParams if active_trading or not SIM: buyDec = buyDecision(obj, symb[e], defPolicy) sellDec = sellDecision(obj, symb[e], defPolicy) if (sellDec[1] == 'sell'): sell_matrix.append( [sellDec[0], symb[e], sellDec[2], sellDec[3]]) if (buyDec[1] == 'buy'): buy_matrix.append([buyDec[0], symb[e], buyDec[2], buyDec[3]]) sell_matrix = sorted(sell_matrix) buy_matrix = sorted(buy_matrix) buy_matrix = buy_matrix[0:2] while len(sell_matrix) > 0: if (sell_matrix[-1][2] > 0.001): updateBalanceAndPosition(sell_matrix[-1][1], 'sell', 0, sell_matrix[-1][3]) if not SIM: resetToken() token_change = True time.sleep(1) sell(sell_matrix[-1][1], sell_matrix[-1][2]) sell_matrix.pop() if not SIM and len(buy_matrix) > 0: if not token_change: resetToken() balance = getBalance() #retrieve buy amounts for each listed stock after sell-offs buy_matrix = buyAmounts(buy_matrix, withPolicy) if len(buy_matrix) > 0: max_spend_rolling -= 0.1 while len(buy_matrix) > 0 and balance > 0: if (buy_matrix[-1][4] > 0.001): if spent_today < max_daily_spend * initialBalance: updateBalanceAndPosition(buy_matrix[-1][1], 'buy', buy_matrix[-1][4], buy_matrix[-1][3]) if not SIM: time.sleep(1) buy(buy_matrix[-1][1], buy_matrix[-1][4]) buy_matrix.pop()
while(True): q = get_quote(venue, symbol) bid = 1 bought = False sold = False if(q.bidSize > 0): bid = q.bid + 1 ask = 9999999 if(q.askSize > 0): ask = q.ask - 1 if(qty < 900): b = buy(account, venue, symbol, bid, 100) bought = True if(qty > -900): s = sell(account, venue, symbol, ask, 100) sold = True time.sleep(.5) if(bought): bo = cancel_order(venue, symbol, b.id) for f in bo.fills: qty = qty + f.qty position = position - (f.qty * f.price) if(sold): so = cancel_order(venue, symbol, s.id)
import time from api import buy, get_quote venue = 'BMSTEX' symbol = 'YMRI' account = 'PFB66379220' i = 0 while(i < 100): q = get_quote(venue, symbol) if(q.askSize > 0): print(q) o = buy(account, venue, symbol, q.ask, 1000) print (o) time.sleep(1)