def doTrade(pool, prices, ps, fast, slow, rsiPeriod, rsiGuage): sname = 'L2_' + str(fast) + '_' + str(slow) + '_' + str(rsiPeriod) + '_' + str(rsiGuage) macds = macd.calc_macd(prices, fast, slow, 7) rsis = rsi.calc_rsi(prices, rsiPeriod) front = max(fast, slow, rsiPeriod) t = Trader(sname) direct = odirect = 0 for i in range(front, len(prices)): #print macds['macd'][i], rsis['rsi'][i], odirect , direct price = prices[i] if macds['macd'][i] > 0 and rsis['rsi'][i] > rsiGuage: direct = 1 elif macds['macd'][i] < 0 and rsis['rsi'][i] < rsiGuage: 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
def test_cancel_order_fail(): """ 测试取消报单但失败 """ openLimitPrice = 1000 trader = Trader() # 尝试创建头寸 toOrder = trader.openPosition( instrumentId=getDefaultInstrumentId(), direction='buy', volume=1, openLimitPrice=openLimitPrice ) # 发起撤单请求 order = trader.cancelOrder(toOrder.id) assert order.order == toOrder assert order.action == 'cancel' assert order.state == 'insert' assert order.finishTime is None # 发起撤单失败 errorId = -1 errorMsg = u'测试' trader.onCancelOrderError(order, errorId, errorMsg, toOrder) toOrder = ModelOrder.objects.get(id=toOrder.id) order = ModelOrder.objects.get(id=order.id) position = toOrder.position assert order.state == 'error' assert order.finishTime is not None assert order.errorId == errorId assert order.errorMsg == errorMsg assert toOrder.state in ('insert', 'finish') assert position.state in ('preopen', 'open')
def loader(): q = Loader.quote_lookup() print(q) with Database() as db: db.cursor.execute('''SELECT stop_loss FROM log;''') all_stop_loss = db.cursor.fetchall() try: latest_stop_loss = all_stop_loss[-1][0] except: pass with Database() as db: try: db.cursor.execute( '''SELECT ticker from log WHERE stop_loss="{}"; '''.format(latest_stop_loss)) ticker = db.cursor.fetchone()[0] tick = ticker.lower() tick_current = q['{}_current'.format(tick)] if latest_stop_loss >= tick_current: if tick == 'tvix': return Trader.tvix_sell_gains(tick_current) else: return Trader.svxy_sell_gains(tick_current) else: return tracker(q) except: return tracker(q)
def __init__(self): self.driver = webdriver.Chrome() self.trader = Trader(self.driver, 3) self.trader.login() self.stockselector = None self.stockpredictor = None self.portfolio = {}
def __init__(self, node, rationale, **kw): ResourceAgent.__init__(self, node) Trader.__init__(self, rationale, **kw) self.trace = Tracer(node) self.trace = self.trace.add('%-12s' % self) self.listen_process = None self.quote_timeouts = dict()
def doMaTrade(pool, ft, f, s1t, s1, s2t, s2): global prices sname = ft + '_' + str(f) + '_' + s1t + '_' + str(s1) + '_' + s2t + '_' + str(s2) fma, s1ma, s2ma = getMas(ft, f), getMas(s1t, s1), getMas(s2t, s2) t = Trader(sname) #t.args = [ft, f, s1t, s1, s2t, s2] front = max(s1, s2) for i in range(front, len(prices)): price = prices[i] 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=0, notes=notes) pool.estimate(t)
def __init__(self, job, rationale, **kw): JobAgent.__init__(self, job) Trader.__init__(self, rationale, **kw) self.migrations = 0 self.listen_process = None self.accepted = set()
def test_cancel_order_success(): """ 测试取消报单并成功 """ openLimitPrice = 1000 trader = Trader() # 尝试创建头寸 toOrder = trader.openPosition( instrumentId=getDefaultInstrumentId(), direction='buy', volume=1, openLimitPrice=openLimitPrice ) # 发起撤单请求 order = trader.cancelOrder(toOrder.id) assert order.order == toOrder assert order.action == 'cancel' assert order.state == 'insert' assert order.finishTime is None # 发起撤单成功 trader.onOrderCanceled(order, toOrder) toOrder = ModelOrder.objects.get(id=toOrder.id) order = ModelOrder.objects.get(id=order.id) position = toOrder.position assert order.state == 'finish' assert order.finishTime is not None assert toOrder.state == 'cancel' assert toOrder.finishTime is not None assert position.state == 'cancel'
def _init_options(self, **options): try: self.m_type = options['market'] except KeyError: self.m_type = 'stock' try: self.init_cash = options['cash'] except KeyError: self.init_cash = 100000 try: self.logger = options['logger'] except KeyError: self.logger = None try: self.use_sequence = options['use_sequence'] except KeyError: self.use_sequence = False try: self.use_normalized = options['use_normalized'] except KeyError: self.use_normalized = True try: self.mix_trader_state = options['mix_trader_state'] except KeyError: self.mix_trader_state = True try: self.mix_index_state = options['mix_index_state'] except KeyError: self.mix_index_state = False finally: if self.mix_index_state: self.index_codes.append('sh') try: self.seq_length = options['seq_length'] except KeyError: self.seq_length = 5 finally: self.seq_length = self.seq_length if self.seq_length > 1 else 2 try: self.training_data_ratio = options['training_data_ratio'] except KeyError: self.training_data_ratio = 0.7 try: scalar = options['scaler'] except KeyError: scalar = StandardScaler self.state_codes = self.codes + self.index_codes self.scalar = [scalar() for _ in self.state_codes] self.trader = Trader(self, cash=self.init_cash)
def __init__(self, dbinfo): self.mysql_client = CMySQL(dbinfo) self.cal_client = ccalendar.CCalendar(without_init=True) with open(ct.USER_FILE) as f: infos = json.load(f) self.trader = Trader(infos[0]["account"], infos[0]["passwd_encrypted"], infos[0]["secuids_sh"], infos[0]["secuids_sz"]) self.bnew_succeed_date = ""
async def trader_init(self, ctx, override=False): if ctx.message.author.id != ADMIN and not override: await ctx.send(AUTH_ERR) else: self.trader = Trader() self.trader.load() await ctx.send("Trader initialized and loaded")
def test_close_position_error(): """ 测试关闭头寸出错的情况 """ flag = [] def onClosePositionError(order, errorId, errorMsg, position=None): flag.append([order, errorId, errorMsg, position]) trader = Trader() trader.bind('onClosePositionError', onClosePositionError) # 创建一个头寸并关闭它 openOrder = trader.openPosition(getDefaultInstrumentId(), 'buy', 1) position = openOrder.position trader.onPositionOpened(openOrder, position) assert position.state == 'open' closeOrder = trader.closePosition(position.id) position = ModelPosition.objects.get(id=position.id) # 模拟头寸创建失败事件 errorId = -1 errorMsg = u'测试' trader.onClosePositionError(closeOrder, errorId, errorMsg, position) assert closeOrder.state == 'error' assert closeOrder.finishTime is not None assert closeOrder.errorId == errorId assert closeOrder.errorMsg == errorMsg assert position.state == 'open' assert position.closeTime is None # 检查事件正常传递 assert len(flag) == 1 assert flag[0][0] == closeOrder assert flag[0][1] == errorId assert flag[0][2] == errorMsg assert flag[0][3] == position
def predict_trade(test_data, capital, window_size=10): total_profit = 0 closes = [] buys = [] sells = [] done = True trader = Trader(window_size, True) trader.portfolio = [] num_steps = len(test_data) - 1 batch_size = 32 state = state_normalize(test_data, 0, window_size + 1) for t in range(num_steps): action = trader.act(state) closes.append(test_data[t]) next_state = state_normalize(test_data, t + 1, window_size + 1) reward = 0 # buy if action == 1: if capital > test_data[t]: trader.portfolio.append(test_data[t]) buys.append(test_data[t]) sells.append(None) capital -= test_data[t] else: buys.append(None) sells.append(None) # sell elif action == 2: if len(trader.portfolio) > 0: bought_price = trader.portfolio.pop(0) reward = max(test_data[t] - bought_price, 0) total_profit += test_data[t] - bought_price buys.append(None) sells.append(test_data[t]) capital += test_data[t] else: buys.append(None) sells.append(None) elif action == 0: buys.append(None) sells.append(None) if t == num_steps - 1: done = True trader.history.push(state, action, next_state, reward) state = next_state plot_actions(closes, buys, sells, total_profit) return total_profit
class CTrader: def __init__(self, dbinfo): self.mysql_client = CMySQL(dbinfo) self.cal_client = ccalendar.CCalendar(without_init=True) with open(ct.USER_FILE) as f: infos = json.load(f) self.trader = Trader(infos[0]["account"], infos[0]["passwd_encrypted"], infos[0]["secuids_sh"], infos[0]["secuids_sz"]) self.bnew_succeed_date = "" def buy_new_stock(self, sleep_time): while True: try: if self.cal_client.is_trading_day(): _today = datetime.now().strftime('%Y-%m-%d') if self.bnew_succeed_date != _today: n_list = self.get_new_stock_list() if len(n_list) == 0: logger.info("no new stock for %s." % _today) self.bnew_succeed_date = _today return for stock in n_list: ret, amount = self.trader.max_amounts( stock[0], stock[1]) if 0 == ret: ret, msg = self.trader.deal( stock[0], stock[1], amount, "B") if ret == 0: logger.info( "buy new stock:%s for %s succeed" % (stock, _today)) self.bnew_succeed_date = _today else: logger.error( "buy new stock:%s for %s error, msg:%s" % (stock, _today, msg)) except Exception as e: logger.info(e) traceback.print_exc() time.sleep(sleep_time) def get_new_stock_list(self): stock_list = [] top_stocks_info = ts.new_stocks().head(STOCK_NUM) stocks_info = top_stocks_info[[ IPO_CODE_HEAD, IPO_DATE_HEAD, IPO_PRICE_HEAD ]] for i in range(STOCK_NUM): stock_date = stocks_info.at[i, IPO_DATE_HEAD] if pd.to_datetime(stock_date).strftime( '%Y-%m-%d') == datetime.now().strftime('%Y-%m-%d'): code = stocks_info.at[i, IPO_CODE_HEAD] price = stocks_info.at[i, IPO_PRICE_HEAD] stock_list.append((code, price)) return stock_list
def get_market_data(): global username if request.method == "GET": band1 = Bandit() trader1 = Trader() police1 = Police() cost1 = Cost() market_inventory = regions.child(currRegion).child('inventory').get() ship_inventory = users.child(username).child('ship').child( 'inventory').get() difficulty = users.child(username).child('difficulty').get() ship_cargo = users.child(username).child('ship').child('cargo').get() credit_val = users.child(username).child('credit').get() ship_health = users.child(username).child('ship').child('health').get() pilot_skill = users.child(username).child('skills').child( 'pilot').get() engineer = users.child(username).child('skills').child( 'engineer').get() fighter_skill = users.child(username).child('skills').child( 'fighter').get() merchant_skill = users.child(username).child('skills').child( 'merchant').get() fuel = users.child(username).child('ship').child('fuel').get() fuelcost = cost1.calculate_fuel(difficulty, credit_val) demand = band1.calculate_demand(difficulty, credit_val) repair = cost1.calculate_repair(difficulty, engineer, credit_val) price = trader1.item_to_sell(difficulty, credit_val) qty = trader1.qty item = trader1.item stolen = police1.stolen_item(ship_inventory) to_return = { 'username': username, 'currRegion': currRegion, 'market_inventory': market_inventory, 'ship_inventory': ship_inventory, 'cargo': ship_cargo, 'credit': credit_val, 'health': ship_health, 'demand': demand, 'qty': qty, 'item': item, 'price': price, 'eng': engineer, 'stolen': stolen, 'difficulty': difficulty, 'pilot': pilot_skill, 'fighter': fighter_skill, 'fuel': fuel, 'fuelcost': fuelcost, 'merch': merchant_skill, 'repair': repair } return to_return return None
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
def trade_stock_make_profit(self, config, stock_df, use_predictions): if use_predictions: trade_df = stock_df[['Adj. Close', 'Trade Signal']] config['name'] += ' with predictions' else: trade_df = stock_df[['Adj. Close', 'Current Signal']] config['name'] += ' no predictions' trader = Trader(config) trader.trade(trade_df) return trader.profit
def __init__(self): rospy.init_node('cryptomaster') self.state = states.WAITING_FOR_MAP self.action_client = SimpleActionClient("move_base", MoveBaseAction) self.action_client.wait_for_server() self.goal_generator = GoalGenerator( rospy.get_param('~img'), erosion_factor=rospy.get_param('~erosion'), goal_step=rospy.get_param('~step')) self.hand_manipulator = HandManipulator() self.circle_clusterer = Clusterer( "cluster/point", min_center_detections=18, expected_clusters_count=NUM_CIRCLES_TO_DETECT) self.cylinder_clusterer = Clusterer( "cluster/cylinder", min_center_detections=15, expected_clusters_count=NUM_CYLINDERS) self.trader = Trader() self.cv_map = None self.map_transform = None self.map_resolution = 0 self.viewpoints = None self.goals_left = None self.robot_location = Point(100.0, 15.0, 0.0) self.coins_dropped = 0 self.circles_approached = 0 self.state_handlers = { states.READY_FOR_GOAL: self.ready_for_goal_state_handler, states.WAITING_FOR_MAP: self.map_state_handler, states.GOALS_VISITED: self.goals_visited_handler } _ = rospy.Subscriber("map", OccupancyGrid, self.map_callback) self.arm_publisher = rospy.Publisher("set_manipulator_position", Int8, queue_size=10) self.state_publisher = rospy.Publisher("engine/status", String, queue_size=10) self.velocity_publisher = rospy.Publisher('cmd_vel_mux/input/navi', Twist, queue_size=10) self.speaker_publisher = rospy.Publisher("speaker/say", String, queue_size=10) self.engine_state_publisher = rospy.Publisher("engine/status", String, queue_size=10)
def __init__(self, ticker, starting_balance, trade_pct, fee_pct, tick_size): self._ticker = ticker self._tick_size = tick_size self._starting_balance = starting_balance self._trade_pct = trade_pct self._fee_pct = fee_pct self.reset() self._ticks_per_state = 14 starting_ticks = self._ticker.get_bulk(self._ticks_per_state, groups=self._tick_size) self._trader = Trader(starting_ticks, self._starting_balance) self.num_states = self._trader.num_states self.num_actions = 4
def doKDJTrade(pool, prices, kPeriod, dPeriod, slowing): global highest sname = 'KDJ_' + str(kPeriod) + '_' + str(dPeriod) + '_' + str(slowing) kds = kdj.calc_kd(prices, kPeriod, dPeriod, slowing) t = Trader(sname) for i in range(kPeriod + slowing, len(prices)): if kds['k'][i - 1] <= 30 and kds['k'][i - 1] < kds['d'][ i - 1] and kds['k'][i] > kds['d'][i]: notes = 'KDJ: pre' + str(kds['k'][i - 1]) + ';' + str( kds['d'][i - 1]) + ';cur: ' + str(kds['k'][i]) + ';' + str( kds['d'][i]) t.buy(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes) if kds['k'][i - 1] >= 70 and kds['k'][i - 1] > kds['d'][ i - 1] and kds['k'][i] < kds['d'][i]: notes = 'KDJ: pre' + str(kds['k'][i - 1]) + ';' + str( kds['d'][i - 1]) + ';cur: ' + str(kds['k'][i]) + ';' + str( kds['d'][i]) t.sell(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes) t.show(prices[i]['date'], prices[i]['time'], prices[i]['rmb']) pool.estimate(t)
def main_loop(_trade_env): trader = Trader(_trade_env) try: while True: _logger.info('trading...') trader.trade() _logger.info('retry after 10 s ...') time.sleep(10) except Exception as e: print(e) _logger.error(e) _logger.error(traceback.format_exc()) finally: pass
def setup_rand_trader(self): name = ''.join( random.choices(string.ascii_uppercase + string.digits, k=10)) bid_or_ask = rd.rand_trader_type() funds = rd.trader_funds(self.clearing_price, bid_or_ask) trader = Trader(name, funds) p_low, p_high = rd.rand_prices(self.clearing_price, bid_or_ask) trader.enter_order( bid_or_ask, # 'bid', 'ask' p_high, # p_high p_low, # p_low rd.rand_u_max(10), # u_max rd.rand_q_max(100)) # q_max self.traders[name] = trader return trader
def doTrade(pool, prices, ps, near, far): sname = 'L2_' + str(near) + '_' + str(far) phighs = [p['high'] for p in prices] plows = [p['low'] for p in prices] front = max(near, far) t = Trader(sname) direct = odirect = 0 for i in range(front, len(prices)): price = prices[i] span = 3 if phighs[i] > phighs[i - 1] and plows[i] > plows[i - 1]: nearLow, nearLowIndex = findLow(phighs, plows, i - span + 1, i) nearHigh, nearHighIndex = findHigh(phighs, plows, nearLowIndex - span + 1, nearLowIndex) farLow, farLowIndex = findLow(phighs, plows, nearHighIndex - span + 1, nearHighIndex) farHigh, farHighIndex = findHigh(phighs, plows, farLowIndex - span + 1, farLowIndex) elif phighs[i] < phighs[i - 1] and plows[i] > plows[i - 1]: nearHigh, nearHighIndex = findHigh(phighs, plows, i - span + 1, i) nearLow, nearLowIndex = findLow(phighs, plows, nearHighIndex - span + 1, nearHighIndex) farHigh, farHighIndex = findHigh(phighs, plows, nearLowIndex - span + 1, nearLowIndex) farLow, farLowIndex = findLow(phighs, plows, farHighIndex - span + 1, farHighIndex) else: continue for j in range(i - span + 1, i + 1): if phighs[j] > nearHigh: nearHigh, nearHignIndex = phighs[j], j if plows[j] < nearLow: nearLow, nearLowIndex = plows[j], j if nearHignIndex = i
def main(): api_key = None OAUTH2_TEMP = None # Edit this value with your api_key or oauth2credenial, uncomment the one you choose to use # api_key = "longcharacterstring of api_key given by coinbase" # OAUTH2_TEMP ='''{"_module": "oauth2client.client", "token_expiry": "2013-03-31T22:48:20Z", "access_token": "c15a9f84e471db9b0b8fb94f3cb83f08867b4e00cb823f49ead771e928af5c79", "token_uri": "https://www.coinbase.com/oauth/token", "invalid": false, "token_response": {"access_token": "c15a9f84e471db9b0b8fb94f3cb83f08867b4e00cb823f49ead771e928af5c79", "token_type": "bearer", "expires_in": 7200, "refresh_token": "90cb2424ddc39f6668da41a7b46dfd5a729ac9030e19e05fd95bb1880ad07e65", "scope": "all"}, "client_id": "2df06cb383f4ffffac20e257244708c78a1150d128f37d420f11fdc069a914fc", "id_token": null, "client_secret": "7caedd79052d7e29aa0f2700980247e499ce85381e70e4a44de0c08f25bded8a", "revoke_uri": "https://accounts.google.com/o/oauth2/revoke", "_class": "OAuth2Credentials", "refresh_token": "90cb2424ddc39f6668da41a7b46dfd5a729ac9030e19e05fd95bb1880ad07e65", "user_agent": null}''' if raw_input("Do you want to try to execute trades? Type 'YES':") == 'YES': # IF VALID CREDENTIALS THESE TRADES WILL ATTEMPT TO EXECUTE BE CAREFUL!!! myTrader = Trader(api_key=api_key, oauth2_credentials=OAUTH2_TEMP) print 'Sell no lower than 1500 usd/btc' myTrader.setLimitSell(qty=0.3, price=1500) print 'Buy no higher than 500 usd/btc' myTrader.setLimitBuy(qty=0.2, price=500) print 'Sell if the price drops 10% from the max value seen by .trade()' myTrader.setTrailStopLossPercent(qty=0.3, changeval=10) ##### Example of oneStartsAnother() Order, first the sell order is triggered followed by the buy ##### # order1 = myTrader.setLimitSell(qty= 0.15, price = 700, queue=False) # order2 = myTrader.setLimitBuy(qty = 0.15, price = 600, queue=False) # myTrader.oneStartsAnother(order1, order2) print 'Start attempting to execute the orders with .trade' myTrader.trade(sleeptime=60) # Treading version commented out below ####### Setup for both options ####### # myTrader.trade(sleeptime = 30, startNewThread = True) ###### Option 1, accept user input ###### # while 1: # userInput = raw_input("") # eval(userInput) # Then type myTrader.set ###### Option 2, add more orders based on a trading algorithm you wrote ####### # ### This is mostly sudo code to give you an idea of something you could do # allmymoney = 100 # while 1: # buyprice = myTrade.account.buy_price(qty = myqty) # sellprice = myTrade.account.sell_price(qty = myqty) # otherdata = getdata() # getModel(testdata) # nextHourEstimate = makePrediction(buyprice,sellprice,otherdata) # if getGains(nextHourEstimate, buyprice, sellprice) == 0.02: # addOrder(myTrader, nextHourEstimate, buyprice, sellprice) # testdata.addData(buyprice, sellprice, otherdata) # time.sleep(3600) else: print "if thats the case I suggest you enter in values that won't execute or attempt to sell" print "if you sell and don't have coins coinbase will return an error and the trade won't be executed"
def __init__(self, dbinfo, fpath = ct.USER_FILE): self.mysql_client = CMySQL(dbinfo) self.cal_client = ccalendar.CCalendar(without_init = True) with open(fpath) as f: infos = json.load(f) self.traders = list() for info in infos: self.traders.append(Trader(info["account"], info["passwd_encrypted"], info["secuids_sh"], info["secuids_sz"])) self.buy_succeed_date = ""
def setup_traders(num_traders): traders = [] # order_type = ['buy', 'sell', 'C', 'poop'] order_type = ['buy', 'sell'] print(f'Creating {num_traders} new traders and sending orders:') for i in range(0, num_traders): name = f'Trader{i}' trader = Trader(name, random.randint(50, 300)) trader.new_order( random.choice(order_type), # 'buy', 'sell' random.randint(101, 120), # p_high random.randint(80, 99), # p_low random.randint(400, 500), # u_max random.randint(1000, 2000)) # q_max traders.append(trader) # print(trader.current_order) return traders
def middleBandSurfer(self, currency ): """ this bot will first check the slope of the 50/sma and BBands middle band making sure it's in an incline, then it will check if a candle from above touces the center line. It will then execute a buy to best buy bot to trail the buy signal to it's bottom the sell middleBandSurferSell counterpart bot will profit is above margin and price touches the upper band. It will then go to best sell bot to trail the price higher for the ideal sell """ csdata = Trader(currency=currency).get_candlesticks("24h","5m") market = CoinCalc.getInstance().get_market(currency) analyzer = Analyzer( csdata ) analyzer.add_indicator("macd",{}) analyzer.add_indicator("bbands",{}) analyzer.add_indicator("sma",{}) analyzer.add_indicator("rsi",{"overbought":70,"oversold":30,"period":14}) idata = analyzer.process() macd = idata["macd"]["analysis"] bbands = idata["bbands"]["analysis"] rsi = idata["rsi"]["analysis"] sma = idata["sma"]["analysis"] mysignal = None price_entry = None if self.last_trade + self.min_trade_freq < time.time(): #if bbands["slope"] > 1 and csdata["closed"][-1] < bbands["m"] and bbands["d"] > 35 and rsi["signal"] == "oversold": if csdata["closed"][-2] > bbands["m"] and csdata["closed"][-1] < bbands["m"] and bbands["d"] > 35 and rsi["signal"] == "oversold": mysignal = "oversold" price_entry = csdata["closed"][-1] #elif bbands["slope"] > 1 and csdata["closed"][-1] > bbands["t"] and bbands["d"] > 35 and rsi["signal"] == "overbought": elif csdata["closed"][-1] > bbands["t"] and bbands["d"] > 35 and rsi["signal"] == "overbought": mysignal = "overbought" price_exit = csdata["closed"][-1] else: mysignal = "cooldown" self.set_data({ "result": { "details": { "botname": "middleBandSurfer", "last": csdata["closed"][-1], "price_entry": price_entry, "signal": mysignal, "time":time.time() }, "exchange": "bittrex", "market": market, "currency": currency, "trade_amount": self.max_trade_amount, "cs_time": csdata["time"][-1] }, "indicators": [macd,bbands,sma,rsi] }) return self
class Engine(object): def __init__(self, time_window=5, interval=1, bb_length=3): #Update interval self.interval = interval #Time window to visualize self.time_window = time_window #Create the Data() object self.data = Data(buffer_days=self.time_window) #Initialize the object self.data.init_data(self.interval) #Initialize and use the bollingerbands self.data.init_bollingerbands(length=bb_length) #Initialize the trader agent self.trader = Trader(self.data) def run(self, loops=10000): counter = 0 while (counter < loops): # Print the dataset ## print(self.data.historic_data) #Print loop number: #print('Loop: ' + str(counter) + ' Price:' + str(self.data.historic_data['Price'].iloc[-1]) +'\tShares: ' + # str(self.trader.current_stocks)) # Exec the trading self.trader.trade() # Wait the interval time.sleep(self.interval) # Update the historic dataset self.data.update_data() # Counter++ counter += 1
def load_config(): required_params = {"exchange":None,"public_key":None,"private_key":None,"pair":None,"amount":None} optional_params = {"stoploss":7,"charting":"candlestick","period_length":60} traders = [] config_file = open('margaret_config.json','r') config = json.loads(config_file.read()) config_file.close() for name,params in config.items(): for key in required_params: required_params[key] = params[key] for key in optional_params: if key in params: optional_params[key] = params[key] r = required_params o = optional_params trader = Trader(name,r['exchange'],r['public_key'],r['private_key'],r['pair'],r['amount'], period_length=o['period_length'],\ charting=o['charting'],\ stoploss=o['stoploss']) try: trader.restore(trader.get_historical()) except: pass indicator_config(trader,params['indicator_config']) i = params['indicator'] if len(i) == 2: indicators = {"emacrossover":trader.ema,"smacrossover":trader.sma,"donchianchannels":trader.donchian_breakout} trader.config_dual_indicator(indicators[i[0]],indicators[i[1]]) trader.set_indicator("dual_indicator") else: trader.set_indicator(i[0]) traders.append(trader) return traders
def doTrade(pool, prices, ps, risk, ssp): sname = 'L2_' + str(risk) + '_' + str(ssp) #k = 33 - risk phighs = [p['high'] for p in prices] plows = [p['low'] for p in prices] pdiff = map(lambda f, s: f - s, phighs, plows) front = max(0, ssp) 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
def __init__(self, time_window=5, interval=1, bb_length=3): #Update interval self.interval = interval #Time window to visualize self.time_window = time_window #Create the Data() object self.data = Data(buffer_days=self.time_window) #Initialize the object self.data.init_data(self.interval) #Initialize and use the bollingerbands self.data.init_bollingerbands(length=bb_length) #Initialize the trader agent self.trader = Trader(self.data)
def lineup_traders(self, tickers): global ml count = 1 for ticker in tickers: self.traders.append(Trader(count, ticker, self.account)) Notify.info(f"Successfully connected Trader #{count} to {ticker}", delay=0.01) count += 1 self.logger.info("Trader lineup complete") print("")
def main(): api_key = None OAUTH2_TEMP = None # Edit this value with your api_key or oauth2credenial, uncomment the one you choose to use # api_key = "longcharacterstring of api_key given by coinbase" # OAUTH2_TEMP ='''{"_module": "oauth2client.client", "token_expiry": "2013-03-31T22:48:20Z", "access_token": "c15a9f84e471db9b0b8fb94f3cb83f08867b4e00cb823f49ead771e928af5c79", "token_uri": "https://www.coinbase.com/oauth/token", "invalid": false, "token_response": {"access_token": "c15a9f84e471db9b0b8fb94f3cb83f08867b4e00cb823f49ead771e928af5c79", "token_type": "bearer", "expires_in": 7200, "refresh_token": "90cb2424ddc39f6668da41a7b46dfd5a729ac9030e19e05fd95bb1880ad07e65", "scope": "all"}, "client_id": "2df06cb383f4ffffac20e257244708c78a1150d128f37d420f11fdc069a914fc", "id_token": null, "client_secret": "7caedd79052d7e29aa0f2700980247e499ce85381e70e4a44de0c08f25bded8a", "revoke_uri": "https://accounts.google.com/o/oauth2/revoke", "_class": "OAuth2Credentials", "refresh_token": "90cb2424ddc39f6668da41a7b46dfd5a729ac9030e19e05fd95bb1880ad07e65", "user_agent": null}''' if raw_input("Do you want to try to execute trades? Type 'YES':") == "YES": # IF VALID CREDENTIALS THESE TRADES WILL ATTEMPT TO EXECUTE BE CAREFUL!!! myTrader = Trader(api_key=api_key, oauth2_credentials=OAUTH2_TEMP) print "Sell no lower than 1500 usd/btc" myTrader.setLimitSell(qty=0.3, price=1500) print "Buy no higher than 500 usd/btc" myTrader.setLimitBuy(qty=0.2, price=500) print "Sell if the price drops 10% from the max value seen by .trade()" myTrader.setTrailStopLossPercent(qty=0.3, changeval=10) ##### Example of oneStartsAnother() Order, first the sell order is triggered followed by the buy ##### # order1 = myTrader.setLimitSell(qty= 0.15, price = 700, queue=False) # order2 = myTrader.setLimitBuy(qty = 0.15, price = 600, queue=False) # myTrader.oneStartsAnother(order1, order2) print "Start attempting to execute the orders with .trade" myTrader.trade(sleeptime=60) # Treading version commented out below ####### Setup for both options ####### # myTrader.trade(sleeptime = 30, startNewThread = True) ###### Option 1, accept user input ###### # while 1: # userInput = raw_input("") # eval(userInput) # Then type myTrader.set ###### Option 2, add more orders based on a trading algorithm you wrote ####### # ### This is mostly sudo code to give you an idea of something you could do # allmymoney = 100 # while 1: # buyprice = myTrade.account.buy_price(qty = myqty) # sellprice = myTrade.account.sell_price(qty = myqty) # otherdata = getdata() # getModel(testdata) # nextHourEstimate = makePrediction(buyprice,sellprice,otherdata) # if getGains(nextHourEstimate, buyprice, sellprice) == 0.02: # addOrder(myTrader, nextHourEstimate, buyprice, sellprice) # testdata.addData(buyprice, sellprice, otherdata) # time.sleep(3600) else: print "if thats the case I suggest you enter in values that won't execute or attempt to sell" print "if you sell and don't have coins coinbase will return an error and the trade won't be executed"
def test_close_position(): """ 测试关闭头寸 """ flag = [] def onPositionClosed(order, position): flag.append([order, position]) trader = Trader() trader.bind('onPositionClosed', onPositionClosed) # 创建一个头寸供关闭使用 openOrder = trader.openPosition(getDefaultInstrumentId(), 'buy', 1) position = openOrder.position trader.onPositionOpened(openOrder, position) assert position.state == 'open' # 测试头寸关闭操作 closeOrder = trader.closePosition(position.id) assert isinstance(closeOrder, ModelOrder) assert closeOrder.id is not None assert closeOrder.position == position assert closeOrder.action == 'close' assert closeOrder.state == 'insert' assert closeOrder.finishTime is None assert closeOrder.closeLimitPrice == 0 position = ModelPosition.objects.get(id=position.id) assert closeOrder.position == position assert position.state == 'preclose' assert position.closeTime is None assert position.closeLimitPrice == 0 # 模拟头寸正常关闭事件 trader.onPositionClosed(closeOrder, position) assert closeOrder.state == 'finish' assert closeOrder.finishTime is not None assert position.state == 'close' assert position.closeTime is not None # NOTE: 因为trader还为实现议价机制,所以此时价格仍为空 assert position.closePrice is None assert closeOrder.closePrice is None # 检查事件正常传递 assert len(flag) == 1 assert flag[0][0] == closeOrder assert flag[0][1] == position
def get_first_generation(layers) -> list[Trader]: global IDX base_trader = Trader(IDX, MUTATION_RATE, SYMBOL, layers) print(IDX, end='\r') traders = [base_trader] for i in range(IDX+1, IDX+POPULATION_SIZE): print(i, end='\r') if base_trader.brain.model_loaded: traders.append(base_trader.clone_mutate(i)) else: traders.append(Trader(i, MUTATION_RATE, SYMBOL, layers)) # for trader in traders: # trader.tempStore() IDX += POPULATION_SIZE return traders
def test_open_position_error(): """ 测试打开头寸出错的情况 """ flag = [] def onOpenPositionError(order, errorId, errorMsg, position): flag.append([order, errorId, errorMsg, position]) trader = Trader() trader.bind('onOpenPositionError', onOpenPositionError) # 尝试打开头寸的报单 order = trader.openPosition(getDefaultInstrumentId(), 'buy', 1) position = order.position # 模拟打开头寸出错的情况 errorId = -1 errorMsg = u'测试' trader.onOpenPositionError(order, errorId, errorMsg, position) assert order.state == 'error' assert order.errorId == errorId assert order.errorMsg == errorMsg assert position.state == 'error' # 检查事件正常传递 assert len(flag) == 1 assert flag[0][0] == order assert flag[0][1] == errorId assert flag[0][2] == errorMsg assert flag[0][3] == position
def traders(): """Creates 4 * number_per_type traders of equal order type distribution """ number_per_type = 10000 traders = [] orders = [] order_type = ['buy', 'sell', 'C', 'invalid'] for x in range(0, 4): for y in range(0, number_per_type): orders.append(order_type[x]) for i in range(0, 4 * number_per_type): name = f'Trader{i}' trader = Trader(name, random.randint(50, 300)) trader.new_order( orders[i], # 'buy', 'sell', 'c', 'invalid' random.randint(100, 110), # p_high random.randint(90, 100), # p_low random.randint(0, 500), # u_max random.randint(1000, 2000)) # q_max traders.append(trader) return traders
def doTrade(pool, prices, ps, risk, ssp): sname = 'L2_' + str(risk) + '_' + str(ssp) #k = 33 - risk phighs = [p['high'] for p in prices] plows = [p['low'] for p in prices] pdiff = map(lambda f,s: f - s, phighs, plows) front = max(0, ssp) 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
def __init__(self, ib: IB, candles: List[Candle], portfolio: Portfolio, saver: AbstractBaseSaver = PickleSaver(), blotter: AbstractBaseBlotter = CsvBlotter(), exec_model: Optional[BaseExecModel] = None, trader: Optional[Trader] = None, contract_fields: Union[List[str], str] = 'contract', keep_ref: bool = True): self.ib = ib self.candles = candles self.saver = saver self.blotter = blotter self.trader = Trader(ib, blotter) self.exec_model = exec_model or EventDrivenExecModel() self.connect_exec_model() self.keep_ref = keep_ref self.portfolio = portfolio self.connect_portfolio() log.debug(f'manager object initiated: {self}')
def bandSurfer(self, currency ): "this bot initiates a trade" csdata = Trader(currency=currency).get_candlesticks("24h","5m") market = CoinCalc.getInstance().get_market(currency) analyzer = Analyzer( csdata ) analyzer.add_indicator("macd",{}) analyzer.add_indicator("bbands",{}) analyzer.add_indicator("sma",{}) idata = analyzer.process() macd = idata["macd"]["analysis"] bbands = idata["bbands"]["analysis"] sma = idata["sma"]["analysis"] #sma["signal"] = "oversold" mysignal = None price_entry = None if self.last_trade + self.min_trade_freq < time.time(): #if sma["signal"] == "oversold": if ( bbands["signal"] == "oversold" and sma["signal"] == "oversold" ) or (macd["trend"] == "bull" and macd["trend_length"] <= 2 and bbands["signal"] == "oversold"): #if macd["trend"] == "bull" and macd["trend_length"] <= 2 and bbands["signal"] == "oversold": mysignal = "oversold" price_entry = csdata["closed"][-1] if macd["trend"] == "bull" and bbands["signal"] == "overbought": mysignal = "overbought" else: mysignal = "cooldown" self.set_data({ "result": { "details": { "botname": "bandSurfer", "last": csdata["closed"][-1], "price_entry": price_entry, "signal": mysignal, "time":time.time() }, "exchange": "bittrex", "market": market, "currency": currency, "trade_amount": self.max_trade_amount, "cs_time": csdata["time"][-1] }, "indicators": [macd,bbands,sma] }) return self
def checkMarketStatus(self, currency, data=None): if data is None: data = self.datastore[currency] market = CoinCalc.getInstance().get_market(currency) if market: traderTA = Trader(market) self.cs = traderTA.get_candlesticks(self.timeframe, self.framesize) ath = 0 for v in self.cs["high"]: if v > ath: ath = v atl = 9999999 for v in self.cs["low"]: if v < atl: atl = v ret = { "price": { "count": 0, "last": self.cs["closed"][-1], "open": self.cs["open"][-1], "HIGH": ath, "LOW": atl, "time": self.cs["time"][-1], } } for indicator in self.indicators: if indicator == "macd": macd = MACD(self.cs) ret["macd"] = macd.get_analysis(data) elif indicator == "bbands": bb = BBands(self.cs, timeperiod=20, nbdevup=2, nbdevdn=2) ret["bbands"] = bb.get_analysis(data) return ret
def __init__(self): QtGui.QMainWindow.__init__(self) self.setupUi(self) self.retranslateUi(self) os.path.dirname(os.path.abspath(sys.argv[0])) self.setWindowTitle("Trader") self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.WindowMaximized | QtCore.Qt.WindowTitleHint ) css = 'style2.css' with open(css,'r') as fd: self.setStyleSheet(fd.read()) sales = self.load_transactions() self.table.setRowCount(len(sales)) self.table.setColumnCount(4) self.table.setColumnWidth(0, 325) self.table.setColumnWidth(1, 135) self.table.setColumnWidth(2, 135) self.table.setColumnWidth(3, 135) total = 0 rownum = 0 for name in sales: profit = float(sales[name]['buy']) + float(sales[name]['sell']) total += profit #print '============= %22.2f %s %s' % (profit, name, total) self.table.setItem(rownum, 0, QtGui.QTableWidgetItem(name)) self.table.setItem(rownum, 1, QtGui.QTableWidgetItem(Trader.pretty_float(sales[name]['buy']))) self.table.setItem(rownum, 2, QtGui.QTableWidgetItem(Trader.pretty_float(sales[name]['sell']))) self.table.setItem(rownum, 3, QtGui.QTableWidgetItem(Trader.pretty_float(profit))) rownum += 1 print Trader.pretty_float(total) self.show()
def test(self): for code in self.meigaras: (dates, kabuka, regressions) = self.get_data(code) trade_signs = self.get_narita_signs(kabuka) try: i = dates[self.startd] if i < self.trend_days: i = self.trend_days j = dates[self.endd] if i >= j: continue except KeyError: continue trader = Trader(code, dates, kabuka) while i <= j: is_traded = False if trade_signs[i] > 0: if regressions[i] < 0: (interest, spent) = trader.trade("SELL", i) is_traded = True if trade_signs[i] < 0: if regressions[i] > 0: (interest, spent) = trader.trade("BUY", i) is_traded = True if is_traded: self.trade_cnt += 1 self.interest_total += interest if interest > 0: self.win_trade_cnt += 1 else: self.lose_trade_cnt += 1 i += 1 f.log("average=%f, total=%d, win=%d, lose=%d" % \ (self.interest_total/self.trade_cnt, self.trade_cnt, self.win_trade_cnt, self.lose_trade_cnt))
def home(): if request.method == 'POST': names = list(mongo.db.prices500.find({'ticker':request.form['name'].upper()})) tweets = list(mongo.db.tweets500.find({'name':request.form['name'].upper()})) dow = list(mongo.db.prices500.find({'ticker':"DJI"})) result = Trader.buySell(request.form['name'].upper(),"2015-09-21","2015-09-25",1000) return render_template('index.html',name=request.form['name'].upper(), names= round(int(result),2), prices=names[0]['prices'][:10], dow=dow[0]['prices'][:10]) else: #stocks = ['AAPL', 'IBM', 'MMM', 'MSFT', 'ATVI'] #prices = list(mongo.db.prices.find({},{'ticker':1})) #34463bad7e819fc5d858f0af40d3c69e #begin stupid stock picking # # bought = False # highRetweet = 0 # buyDate = '' # sellDate = '' # for thing in prices[0]['tweets']: # reCount = thing['retweet'] # dateStr = parse(thing['date']).strftime('%Y-%m-%d') # if highRetweet < reCount: # highRetweet = reCount # # if reCount > 0 and not bought and buyDate == '': # bought = True # buyDate = dateStr # # if reCount < highRetweet and bought and dateStr > buyDate and sellDate == '': # bought = False # sellDate = dateStr # # print buyDate # print sellDate # print Trader.buySell(ticker, buyDate, sellDate, 1000) # # # print Trader.buySell('DJI', buyDate, sellDate, 1000) return render_template('index.html')
def main(): api_key = None OAUTH2_TEMP = None # Edit this value with your api_key or oauth2credenial, uncomment the one you choose to use # api_key = "longcharacterstring of api_key given by coinbase" # OAUTH2_TEMP ='''{"_module": "oauth2client.client", "token_expiry": "2013-03-31T22:48:20Z", "access_token": "c15a9f84e471db9b0b8fb94f3cb83f08867b4e00cb823f49ead771e928af5c79", "token_uri": "https://www.coinbase.com/oauth/token", "invalid": false, "token_response": {"access_token": "c15a9f84e471db9b0b8fb94f3cb83f08867b4e00cb823f49ead771e928af5c79", "token_type": "bearer", "expires_in": 7200, "refresh_token": "90cb2424ddc39f6668da41a7b46dfd5a729ac9030e19e05fd95bb1880ad07e65", "scope": "all"}, "client_id": "2df06cb383f4ffffac20e257244708c78a1150d128f37d420f11fdc069a914fc", "id_token": null, "client_secret": "7caedd79052d7e29aa0f2700980247e499ce85381e70e4a44de0c08f25bded8a", "revoke_uri": "https://accounts.google.com/o/oauth2/revoke", "_class": "OAuth2Credentials", "refresh_token": "90cb2424ddc39f6668da41a7b46dfd5a729ac9030e19e05fd95bb1880ad07e65", "user_agent": null}''' if raw_input("Do you want to try to execute trades? Type 'YES':") == 'YES': # IF VALID CREDENTIALS THESE TRADES WILL ATTEMPT TO EXECUTE BE CAREFUL!!! myTrader = Trader(api_key = api_key, oauth2_credentials = OAUTH2_TEMP) print 'Sell no lower than 1500 usd/btc' myTrader.setLimitSell(qty= 0.3, price =1500) print 'Buy no higher than 500 usd/btc' myTrader.setLimitBuy(qty = 0.2, price = 500) print 'Sell if the price drops 10% from the max value seen by .trade()' myTrader.setTrailStopLossPercent(qty = 0.3, changeval = 10) print 'Start attempting to execute the orders with .trade' myTrader.trade(sleeptime = 60) else: print "if thats the case I suggest you enter in values that won't execute or attempt to sell" print "if you sell and don't have coins coinbase will return an error and the trade won't be executed"
def doKDJTrade(pool, prices, kPeriod, dPeriod, slowing): global highest sname = 'KDJ_' + str(kPeriod) + '_' + str(dPeriod) + '_' + str(slowing) kds = kdj.calc_kd(prices, kPeriod, dPeriod, slowing) t = Trader(sname) for i in range(kPeriod + slowing, len(prices)): if kds['k'][i-1] <= 30 and kds['k'][i-1] < kds['d'][i-1] and kds['k'][i] > kds['d'][i]: notes = 'KDJ: pre' + str(kds['k'][i-1]) + ';' + str(kds['d'][i-1]) + ';cur: ' + str(kds['k'][i]) + ';' + str(kds['d'][i]) t.buy(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes) if kds['k'][i-1] >= 70 and kds['k'][i-1] > kds['d'][i-1] and kds['k'][i] < kds['d'][i]: notes = 'KDJ: pre' + str(kds['k'][i-1]) + ';' + str(kds['d'][i-1]) + ';cur: ' + str(kds['k'][i]) + ';' + str(kds['d'][i]) t.sell(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes) t.show(prices[i]['date'], prices[i]['time'], prices[i]['rmb']) pool.estimate(t)
def test_open_and_close_position_with_limit_price(): """ 测试使用限价打开和关闭头寸 """ openLimitPrice = 1000 closeLimitPrice = 2000 trader = Trader() # 打开头寸 order = trader.openPosition( instrumentId=getDefaultInstrumentId(), direction='buy', volume=1, openLimitPrice=openLimitPrice ) position = order.position assert order.openLimitPrice == openLimitPrice assert position.openLimitPrice == openLimitPrice # 打开头寸成功 trader.onPositionOpened(order, position) order = ModelOrder.objects.get(id=order.id) position = ModelPosition.objects.get(id=position.id) assert order.openLimitPrice == openLimitPrice assert position.openLimitPrice == openLimitPrice # 关闭头寸 order = trader.closePosition(position.id, closeLimitPrice=closeLimitPrice) position = ModelPosition.objects.get(id=position.id) assert order.closeLimitPrice == closeLimitPrice assert position.closeLimitPrice == closeLimitPrice # 关闭头寸成功 trader.onPositionClosed(order, position) order = ModelOrder.objects.get(id=order.id) position = ModelPosition.objects.get(id=position.id) assert order.closeLimitPrice == closeLimitPrice assert position.closeLimitPrice == closeLimitPrice
def test_open_position(): """ 测试打开头寸 """ flag = [] def onPositionOpened(order, position): flag.append([order, position]) trader = Trader() trader.bind('onPositionOpened', onPositionOpened) # 尝试进行打开头寸报单 order = trader.openPosition(getDefaultInstrumentId(), 'buy', 1) assert isinstance(order, ModelOrder) assert order.id is not None assert order.state == 'insert' assert order.action == 'open' assert order.finishTime is None assert order.openLimitPrice == 0 position = order.position assert isinstance(position, ModelPosition) assert position.id is not None assert position.state == 'preopen' assert position.openTime is None assert position.openLimitPrice == 0 # 模拟头寸创建成功事件发生 trader.onPositionOpened(order, position) assert order.state == 'finish' assert order.finishTime is not None assert position.state == 'open' assert position.openTime is not None assert order.errorId == 0 assert order.errorMsg == "" # NOTE: 因为trader还为实现议价机制,所以此时价格仍为空 assert position.openPrice is None assert order.openPrice is None # 检查绑定事件正常传递 assert len(flag) == 1 assert flag[0][0] == order assert flag[0][1] == position
def doBollingTrade(pool, prices, ps, period, deviate): global highest sname = 'BOLLING_' + str(period) + '_' + str(deviate) bollings = bolling.calc_bolling(prices, period, deviate) t = Trader(sname) for i in range(period, len(prices)): if ps[i-1] > bollings['lower'][i-1] and ps[i] < bollings['lower'][i] and t.bsflag < 1: notes = 'LAST p: ' + str(ps[i - 1]) + ';boll lower: ' + str(bollings['lower'][i-1]) + 'CURRENT p: ' + str(ps[i]) + ';boll lower: ' + str(bollings['lower'][i]) t.buy(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes) if ps[i-1] < bollings['mean'][i-1] and ps[i] >= bollings['mean'][i] and t.bsflag == 1: notes = 'LAST p: ' + str(ps[i - 1]) + ';boll mean: ' + str(bollings['mean'][i-1]) + 'CURRENT p: ' + str(ps[i]) + ';boll mean: ' + str(bollings['mean'][i]) t.buy(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes) if ps[i-1] < bollings['upper'][i-1] and ps[i] > bollings['upper'][i] and t.bsflag > -1: notes = 'LAST p: ' + str(ps[i - 1]) + ';boll upper: ' + str(bollings['upper'][i-1]) + 'CURRENT p: ' + str(ps[i]) + ';boll upper: ' + str(bollings['upper'][i]) t.sell(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes) if ps[i-1] > bollings['mean'][i-1] and ps[i] <= bollings['mean'][i] and t.bsflag == -1: notes = 'LAST p: ' + str(ps[i - 1]) + ';boll mean: ' + str(bollings['mean'][i-1]) + 'CURRENT p: ' + str(ps[i]) + ';boll mean: ' + str(bollings['mean'][i]) t.sell(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes) t.show(prices[i]['date'], prices[i]['time'], prices[i]['rmb']) pool.estimate(t)
def doRSITrade(pool, prices, period, up, down): global highest sname = 'RSI_' + str(period) + '_' + str(up) + '_' + str(down) rsis = rsi.calc_rsi(prices, period) t = Trader(sname) for i in range(period, len(prices)): if rsis['rsi'][i] < down and rsis['rsi'][i-1] >= down: notes = 'RSI: ' + str(rsis['rsi'][i]) + ';pre: ' + str(rsis['rsi'][i-1]) + ';down: ' + str(down) t.buy(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes) if rsis['rsi'][i] >= down and rsis['rsi'][i - 1] < down: notes = 'RSI: ' + str(rsis['rsi'][i]) + ';pre: ' + str(rsis['rsi'][i-1]) + ';down: ' + str(down) t.sell(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes, True) if rsis['rsi'][i] > up and rsis['rsi'][i-1] <= up: notes = 'RSI: ' + str(rsis['rsi'][i]) + ';pre: ' + str(rsis['rsi'][i-1]) + ';up: ' + str(up) t.sell(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes) if rsis['rsi'][i] <= up and rsis['rsi'][i-1] > up: notes = 'RSI: ' + str(rsis['rsi'][i]) + ';pre: ' + str(rsis['rsi'][i-1]) + ';up: ' + str(up) t.buy(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes, True) t.show(prices[i]['date'], prices[i]['time'], prices[i]['rmb']) pool.estimate(t)
def doMacdTrade(pool, prices, ps, fast, slow, sign): global highest, openLevel, closeLevel sname = 'MACD_' + str(fast) + '_' + str(slow) + '_' + str(sign) macds = macd.calc_macd(prices, fast, slow, sign) mas = ma.calc_ema(ps, slow) t = Trader(sname) for i in range(slow + sign, len(prices)): if macds['macd'][i] < 0 and macds['macd'][i] > macds['sign'][i] and macds['macd'][i-1] < macds['sign'][i-1] and abs(macds['macd'][i]) > openLevel and mas[i] > mas[i-1]: notes = 'macd under 0, and abs larger than openlevel' t.buy(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes) if macds['macd'][i] < 0 and macds['macd'][i] > macds['sign'][i] and macds['macd'][i-1] < macds['sign'][i-1] and abs(macds['macd'][i]) > closeLevel and mas[i] > mas[i-1]: notes = 'macd under 0, and abs larger than closelevel' t.buy(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes, True) if macds['macd'][i] > 0 and macds['macd'][i] < macds['sign'][i] and macds['macd'][i-1] > macds['sign'][i-1] and abs(macds['macd'][i]) > openLevel and mas[i] < mas[i-1]: notes = 'macd above 0, and abs larger than openlevel' t.sell(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes) if macds['macd'][i] > 0 and macds['macd'][i] < macds['sign'][i] and macds['macd'][i-1] > macds['sign'][i-1] and abs(macds['macd'][i]) > closeLevel and mas[i] < mas[i-1]: notes = 'macd above 0, and abs larger than closeLevel' t.sell(prices[i]['date'], prices[i]['time'], prices[i]['rmb'], notes, True) t.show(prices[i]['date'], prices[i]['time'], prices[i]['rmb']) pool.estimate(t) return
def doTrade(pool, prices, ps, lPeriod, sPeriod, plusSpan): sname = "S3_" + str(lPeriod) + "_" + str(sPeriod) + "_" + str(plusSpan) t = Trader(sname) front = lPeriod + sPeriod - 1 lastbuy = lastsell = 0 for i in range(front, len(prices)): price = prices[i] ys = ps[i - lPeriod - sPeriod + 2 : i - sPeriod + 2] slope, midy = calc_slope(ys) highSlope, highy, lowSlope, lowy = calc_bands(ys) nSlope, ny = calc_slope(ps[i - sPeriod + 1 : i + 1]) std = round(np.std(ys, dtype=np.float64, ddof=0), 3) # if i == 122: print i - lPeriod - sPeriod + 1, i - sPeriod + 1, highSlope, lowSlope x = lPeriod + sPeriod - 2 p = ps[i] volume = 0 notes = "" cntNo = 0 closing = False high, low, mid = highy(x), lowy(x), midy(x) # if slope < 0 and nSlope < 0 and p < high and p > mid and high - p > p - mid and high > mid and mid > low: # notes = '1' # volume = -1 # elif slope > 0 and nSlope > 0 and p > low and p < mid and p - low > mid - p and high > mid and mid > low: # notes = '2' # volume = 1 if p > high and nSlope > 0 and high > mid and mid > low: notes = "3" volume = 1 elif p < low and nSlope < 0 and high > mid and mid > low: notes = "4" volume = -1 if volume == 1 and ((t.counters[0].position > 0 and i - lastbuy < plusSpan) or t.counters[0].position > 3): volume = 0 if volume == -1 and ((t.counters[0].position < 0 and i - lastsell < plusSpan) or t.counters[0].position < -3): volume = 0 if volume == 1: lastbuy = i if volume == -1: lastsell = i if nSlope < 0 and t.counters[0].position > 0 and volume == 0: volume, closing = -1, True if nSlope > 0 and t.counters[0].position < 0 and volume == 0: volume, closing = 1, True # logb.info(str(i) + ',' + str(price['dt']) + ',' + str(std) + ',' + str(notes) + ',' + str(volume) # + ',' + str(p) + ',' + str(low) + ',' + str(mid) + ',' + str(high) + ',' + str(price['rmb']) # + ',' + str(slope) + ',' + str(nSlope)+ ',' + str(highSlope) + ',' + str(lowSlope)) if volume != 0 and i >= 100000: xs = range(lPeriod) upys = map(highy, xs) lowys = map(lowy, xs) midys = map(midy, xs) nxs = range(sPeriod) nys = map(ny, nxs) nxs = map(lambda x: x + lPeriod - 1, nxs) axs = range(lPeriod + sPeriod + 100) ays = ps[i - lPeriod - sPeriod + 2 : i + 102] plt.plot(axs, ays, "b-", xs, midys, "y-", xs, upys, "r-", xs, lowys, "g-", nxs, nys, "c-") plt.title(str(price["dt"]) + " " + str(volume) + " " + str(closing)) plt.show() t.processOrder(price["dt"], price["rmb"], volume, cntNo=cntNo, notes=notes, closing=closing) pool.estimate(t) return t
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
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
import json os.chdir('/home/duhan/github/CTPTrader') filename = 'strategies/sample/config.json' with open(filename) as f: print json.load(f) #%% 创建供测试trader import os os.chdir('/home/duhan/github/CTPTrader') from comhelper import setDjangoEnvironment setDjangoEnvironment() from database.models import ModelAccount from trader import Trader account = ModelAccount.objects.get(id=1) trader = Trader(account) #%% 测试开仓 result = trader.open('IF1508','buy',1) print result[0],result[1],result[2] #%% 测试列出头寸 print trader.getPositionList() #%% 仅列出打开的头寸 print trader.getPositionList(state = 'open') #%% 测试关闭头寸 trader.close(3)
def doTrade(pool, lPeriod, sPeriod, fast, slow, sign): global prices, ps sname = 'Pt_' + str(lPeriod) + '_' + str(sPeriod) + '_' + str(fast) + '_' + str(slow) + '_' + str(sign) if const.currentSecId: sname = const.currentSecId + '_' + sname macds = macd.calc_macd(prices, fast, slow, sign) t = Trader(sname) front = lPeriod + sPeriod - 1 for i in range(front, len(prices)): price = prices[i] volume = 0 notes = '' if t.position == 0 and macds['macd'][i] > 0 and macds['macd'][i] > macds['macd'][i-1]: ys = ps[i - lPeriod - sPeriod + 2 : i - sPeriod + 2] slope, midy = calc_slope(ys) highSlope, highy, lowSlope, lowy = calc_bands(ys) x = lPeriod + sPeriod - 2 p = ps[i] high, low, mid = highy(x), lowy(x), midy(x) if p > high and high > mid and mid > low: notes = 'MACD:' + str(macds['macd'][i]) volume = 1 if t.position > 0 and macds['macd'][i] < 0: notes = 'MACD:' + str(macds['macd'][i]) volume = -1 if volume != 0: t.processOrder(price['dt'], price['trade'], volume * 1000, notes=notes) else: t.summary(price['dt'], price['trade']) if volume == 1 and i < 0: #print i, rsis['rsi'][i] xs = upys = lowys = midys = [] if highy: xs = range(lPeriod) upys = list(map(highy, xs)) lowys = list(map(lowy, xs)) midys = list(map(midy, xs)) #cxs = cys = [] #if cy: # cxs = range(cPeriod) # cys = map(cy, cxs) # cxs = map(lambda x: x + lPeriod - 1, cxs) axs = range(lPeriod + sPeriod + 100) ays = ps[i - lPeriod - sPeriod + 2 : i + 102] if lPeriod + sPeriod + 100 > len(ps): axs = range(len(ps) - lPeriod - sPeriod + 2) ays = ps[i - lPeriod - sPeriod + 2 : ] plt.plot(axs, ays, 'b', xs, midys, 'y', xs, upys, 'r', xs, lowys, 'g') plt.vlines(lPeriod + sPeriod - 2, min(ays), max(ays), color='y', linestyles ='dotted') plt.title(str(price['dt']) + ' ' + str(volume) + ' ' + str(notes)) plt.show() pool.estimate(t) return t
def doTrade(pool, stdPeriod, stdGuage, afmt, af, as1mt, as1, as2mt, as2, bfmt, bf, bs1mt, bs1, bs2mt, bs2): global std, prices sname = str(stdPeriod) + "_" + str(stdGuage) sname += "_" + afmt + "_" + str(af) + "_" + as1mt + "_" + str(as1) if as2 > 0: sname += "_" + as2mt + "_" + str(as2) sname += "_" + bfmt + "_" + str(bf) + "_" + bs1mt + "_" + str(bs1) if bs2 > 0: sname += "_" + bs2mt + "_" + str(bs2) afma, as1ma, as2ma = getMas(afmt, af), getMas(as1mt, as1), getMas(as2mt, as2) bfma, bs1ma, bs2ma = getMas(bfmt, bf), getMas(bs1mt, bs1), getMas(bs2mt, bs2) front = max(as1, as2, bs1, bs2) t = Trader(sname) t.args = [stdPeriod, stdGuage, afmt, af, as1mt, as1, as2mt, as2, bfmt, bf, bs1mt, bs1, bs2mt, bs2] for i in range(front, len(prices)): price = prices[i] if std[stdPeriod][i] > stdGuage: t.switchActiveCounter(1, price["dt"], price["rmb"]) else: t.switchActiveCounter(0, price["dt"], price["rmb"]) # if std[stdPeriod][i] > 1.3: # t.switchActiveCounter(1, price['dt'], price['rmb']) # elif std[stdPeriod][i] > stdGuage: # t.switchActiveCounter(0, price['dt'], price['rmb']) # else: # t.switchActiveCounter(2, price['dt'], price['rmb']) volume = 0 notes = "" if as1 > 0 and afma[i - 1] <= as1ma[i - 1] and afma[i] > as1ma[i]: notes += ( "af>as1;" + str(afma[i - 1]) + ";" + str(as1ma[i - 1]) + ";" + str(afma[i]) + ";" + str(as1ma[i]) + ";" ) volume += 1 if as1 > 0 and afma[i - 1] >= as1ma[i - 1] and afma[i] < as1ma[i]: notes += ( "af<as1;" + str(afma[i - 1]) + ";" + str(as1ma[i - 1]) + ";" + str(afma[i]) + ";" + str(as1ma[i]) + ";" ) volume += -1 if as2 > 0 and afma[i - 1] <= as2ma[i - 1] and afma[i] > as2ma[i]: notes += ( "af>as2;" + str(afma[i - 1]) + ";" + str(as2ma[i - 1]) + ";" + str(afma[i]) + ";" + str(as2ma[i]) + ";" ) volume += 1 if as2 > 0 and afma[i - 1] >= as2ma[i - 1] and afma[i] < as2ma[i]: notes += ( "af<as2;" + str(afma[i - 1]) + ";" + str(as2ma[i - 1]) + ";" + str(afma[i]) + ";" + str(as2ma[i]) + ";" ) volume += -1 t.processOrder(price["dt"], price["rmb"], volume * 1000, cntNo=0, notes=notes) volume = 0 notes = "" if bs1 > 0 and bfma[i - 1] <= bs1ma[i - 1] and bfma[i] > bs1ma[i]: notes += ( "bf>bs1;" + str(bfma[i - 1]) + ";" + str(bs1ma[i - 1]) + ";" + str(bfma[i]) + ";" + str(bs1ma[i]) + ";" ) volume += 1 if bs1 > 0 and bfma[i - 1] >= bs1ma[i - 1] and bfma[i] < bs1ma[i]: notes += ( "bf<bs1," + str(bfma[i - 1]) + ";" + str(bs1ma[i - 1]) + ";" + str(bfma[i]) + ";" + str(bs1ma[i]) + ";" ) volume += -1 if bs2 > 0 and bfma[i - 1] <= bs2ma[i - 1] and bfma[i] > bs2ma[i]: notes += ( "bf>bs2;" + str(bfma[i - 1]) + ";" + str(bs2ma[i - 1]) + ";" + str(bfma[i]) + ";" + str(bs2ma[i]) + ";" ) volume += 1 if bs2 > 0 and bfma[i - 1] >= bs2ma[i - 1] and bfma[i] < bs2ma[i]: notes += "bf<bs2;" + str(bfma[i - 1]) + ";" + str(bs2ma[i - 1]) + ";" + str(bfma[i]) + ";" + str(bs2ma[i]) volume += -1 t.processOrder(price["dt"], price["rmb"], volume * 1000, cntNo=1, notes=notes) pool.estimate(t) print t.stats["equity"] return t
def doTrade(pool, afmt, af, as1mt, as1, as2mt, as2): global std, prices, secId #sname = str(stdPeriod) + '_' + str(stdGuage) sname = afmt + '_' + str(af) + '_' + as1mt + '_' + str(as1) if as2 > 0: sname += '_' + as2mt + '_' + str(as2) if secId: sname = secId + '_' + 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
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