def check_stop_loss(trades_list, account): """ Checks if active trades need stop-losses """ for element in trades_list: trade = Trade(element['instrument'], element['initialUnits'], i_d=element['id'], price=element['price'], take_profit=element['takeProfitOrder']['price'], account=os.environ['trading_url_' + account].split('/')[-2], openTime=element['openTime']) duration = trade.get_trade_duration() if duration >= 3 and 'stopLossOrder' not in element: logging.info(f'Trade to set SL:{trade.i_d} [{duration}h]') try: trade.get_stop_loss() stop_loss = trade.stop_loss order = Order(trade, account) order.set_stop_loss(stop_loss) logging.info(f'SL [{stop_loss}] set for trade ({trade.i_d})') except Exception as e: logging.error( f'No se pudo obtener trade [{trade.i_d}] de la BD ({e})')
def fetch_trades(self, init_period=False): ''' Function to fetch a list of Trade objects Parameter --------- init_period : bool If true, then the CandleList used for the 'period' class attribute will be initialized. Default: False Return ------ list with trades ''' trade_list = [] args = {} for index, row in self.df.iterrows(): pair = re.split(r'\.| ', row['id'])[0] args = {'pair': pair} for c in row.keys(): args[c] = row[c] if init_period is True: t = Trade(**args, init=True) else: t = Trade(**args) trade_list.append(t) return trade_list
def test_trade(): quantity = 10 price = 10 aggressive_order = Order(1, ORDER_BUY_SIDE, 0, price, 1) resting_order = Order(2, ORDER_SELL_SIDE, 1, price, 2) trade = Trade(quantity, price, aggressive_order, resting_order) assert trade.price == price assert trade.quantity == quantity assert trade.aggressive_fill == FILL_TYPE_FULL assert trade.aggressive_quantity == 0 assert trade.aggressive_id == 1 assert trade.resting_fill == FILL_TYPE_PARTIAL assert trade.resting_quantity == 1 assert trade.resting_id == 2 aggressive_order = Order(1, ORDER_BUY_SIDE, 1, price, 1) resting_order = Order(2, ORDER_SELL_SIDE, 0, price, 2) trade = Trade(quantity, price, aggressive_order, resting_order) assert trade.price == price assert trade.quantity == quantity assert trade.aggressive_fill == FILL_TYPE_PARTIAL assert trade.aggressive_quantity == 1 assert trade.aggressive_id == 1 assert trade.resting_fill == FILL_TYPE_FULL assert trade.resting_quantity == 0 assert trade.resting_id == 2
def start(self, mode): if mode == 'SIM': self.trade = TradeSim(self.bitflyer, self.coincheck, self.gmo) else: self.trade = Trade(self.bitflyer, self.coincheck, self.gmo) while True: self.tick() time.sleep(1)
def main(): """Main function Returns: 0 -- exit status """ trade = Trade() trade.run() return SUCCESS
def __init__(self, config, queue, markets, api): self.config = config self.markets = markets self.api = api self.best_ask_bid = BestAskBidAdapter(queue, 'spot_trading','weekly','biweekly','3month') self.trade_pairs = TradePairs() self.trade = Trade(self.api, config, markets) self.scheduler = Scheduler(self.config, self.markets) self.messages = Messages(self.config.config_data['message_language'])
def _process_matched_orders(self, new_order: Order, matched_order_node: Tree): matched_order = matched_order_node.orders[0] # if new_order.qty matches matched_order.qty # 1. register expected: trade, new_order(X), matched_order(X) # 2. remove matched_order from the book # 3. remove the node from the tree if no more orders with same price # new_order fully filled nothing else to do if new_order.qty == matched_order.qty: self._expected_trades.append( Trade(matched_order.qty, matched_order.price)) # add expected Trade self._expected_x_orders.add( new_order.order_id) # add expected new_order(X) self._expected_x_orders.add( matched_order.order_id) # add expected matched_order(X) self._orders_by_id.pop(matched_order_node.orders.popleft().order_id ) # del matched_order from dict and tree new_order.qty = 0 if len(matched_order_node.orders) == 0: matched_order_node.remove_me() # new_order.qty < matched_order.qty # 1. decrease matched_order.qty # 2. register expected messages: trade, new_order(X) # new_order fully filled nothing else to do elif new_order.qty < matched_order.qty: matched_order.qty = matched_order.qty - new_order.qty self._expected_trades.append( Trade(new_order.qty, matched_order.price)) # add expected Trade self._expected_x_orders.add( new_order.order_id) # add expected new_order(X) new_order.qty = 0 # new_order.qty > matched_order.qty # 1. decrease new_order.qty # 2. register expected messages: trade, matched_order(X) # 3. remove matched_order from the book # 4. remove the node from the tree if no more orders with the same price # otherwise recursive call to try to fill the rest of qty else: new_order.qty = new_order.qty - matched_order.qty self._expected_trades.append( Trade(matched_order.qty, matched_order.price)) self._expected_x_orders.add( matched_order.order_id) # add expected matched_order(X) self._orders_by_id.pop(matched_order_node.orders.popleft().order_id ) # del matched_order from dict and tree if len(matched_order_node.orders) == 0: matched_order_node.remove_me() else: self._process_matched_orders(new_order, matched_order_node)
def __init__(self, code_list, init_cash, starttime, endtime): self.starttime = starttime self.endtime = endtime self.data_repository = DataRepository.get_instance(code_list, starttime, endtime) self.code_list = code_list self.init_cash = init_cash self.cash = init_cash self.limited_cash = init_cash/len(code_list) self.position_list = {} for code in self.code_list: self.position_list[code] = 0 #存储trade对象 self.trade = Trade()
def main(): account = 'LWN8306966' venue = 'CNAEX' stock = 'HIJ' price = 3200 qty = 1000 direction = OrderDirection.buy orderType = OrderType.limit waitTime = 10 oldPrice = 0 trade = Trade(account, venue, stock, price, qty, direction, orderType) quote = Quote(venue, stock) vol = 0 while (vol < 100000): quote.refresh() price = choosePrice(quote, trade) # if (price == 2608 or price > 2608): # waitTime = 20 # price = 1700 # else: # waitTime = 1 trade.setPrice(price) trade.setQty(quote.lastSize + 5) trade.prt() response = trade.execute() vol += qty time.sleep(waitTime)
def showCashPanel(self): from panel import CashTrade ct = CashTrade(self.accts) if ct.exec_(): from trade import Trade t = Trade(ct.acct.currentText(), ct.tradeDate.date().toPyDate(), ct.tradeDate.date().toPyDate(), ct.flow.text(), u'现金', 1., float(ct.amount.text()), ct.comment.text(), order_file=False, conf_file=ct.filePath.text() or False) t.toDB() self.tradedatamodel.query().exec_()
def __init__(self, table_name, candle_table_name): self.table_name = table_name self.candle_table_name = candle_table_name if dbm.exists_table(table_name): DBManager.drop_table(table_name) self.table = TradeTable(table_name) self.table.save() candles = CandleTable.get_candle_array(candle_table_name) for c in candles: p = Trade(dbm, table_name, c.date, 0, 0, Trade.NONE_TYPE) p.save() dbm = DBManager.get_instance() dbm.save_and_close()
def run_game(): # Create deck, hand, tableau. deck = Deck() hand = Hand(deck) tableau = Tableau(tableau_limit) trade = Trade() game_end = False # Main game loop. while game_end is False: # Choose action. # phase = gf.choose_action() # Play phases. for phase in range(0, 5): gf.play_phase(phase, deck, hand, tableau, trade) # Check hand limit hand.hand_limit(deck) # Check for game end. game_end = gf.end_check(tableau, scoreboard) return scoreboard.get_vp_total(tableau)
def propose_trade(self, player_id, partner, args): if args[0] in self.trades: return False offer_list = args[2:args.index('want')] want_list = args[args.index('want') + 1:] offer_dict = {} want_dict = {} for x in range(0, len(offer_list), 2): offer_dict[offer_list[x]] = int(offer_list[x + 1]) for x in range(0, len(want_list), 2): want_dict[want_list[x]] = int(want_list[x + 1]) self.trades[args[0]] = Trade(player_id.id, partner, offer_dict, want_dict) msg = '{0} wants to trade with '.format( player_id.mention) + '<@' + str( self.trades[args[0]].partner) + '>\n' msg = msg + 'Contract: ' + args[0] + '\n' msg = msg + 'Offers: ' + str(self.trades[args[0]].offers) + '\n' msg = msg + 'Wants: ' + str(self.trades[args[0]].wants) return msg
async def produce_trades(app): trade = Trade.fake(users_id_up_to=how_many_users_to_use) print(f"Producing trade: {trade}") await trades_stream.send( value=trade, key=str(trade.user_id), )
def _search_for_quantity_in_price_level_partial(self, tick_entry, quantity_to_trade, order): quantity_to_trade -= tick_entry.quantity self._logger.debug("Match with the id (%s) was found for order (%s) ", str(tick_entry.order_id), str(order.order_id)) reserved = order.reserve_quantity_for_tick(tick_entry.tick.order_id, tick_entry.quantity) if not reserved: # Error happened self._logger.warn("Something went wrong") return self._search_for_quantity_in_price_level(tick_entry.next_tick(), quantity_to_trade, order) proposed_trades = [Trade.propose( self.order_book.message_repository.next_identity(), order.order_id, tick_entry.order_id, tick_entry.price, tick_entry.quantity, Timestamp.now() )] # Search the next tick quantity_to_trade, trades = self._search_for_quantity_in_price_level(tick_entry.next_tick(), quantity_to_trade, order) proposed_trades = proposed_trades + trades return quantity_to_trade, proposed_trades
def manage_trade(self): if self.in_trade == False and self.alert == True: self.current_trade = Trade(self.last_date, self.last_price, self.band, self.upper_trade_multipler, self.lower_trade_multipler) self.in_trade = True self.alert = False elif self.in_trade == True: if self.current_trade.band == "UPPER" and self.last_price <= (self.current_trade.alert_price * self.upper_trade_exit): self.exit_position() elif self.current_trade.band == "LOWER" and self.last_price >= (self.current_trade.alert_price * self.lower_trade_exit): self.exit_position() elif self.current_trade.trade_start_day < 2: if self.last_date.weekday() == 2 and self.last_tick == True: self.exit_position() elif self.current_trade.trade_start_day >= 2 and self.current_trade.trade_start_day <= 4: if self.last_date.weekday() == 4 and self.last_tick == True: self.exit_position()
def get_trade(table_name, date): dbm = DBManager.get_instance() cursor = dbm.get_cursor() exec_string = "SELECT * FROM '{tn}' WHERE date = {d}".format( tn=table_name, d=date) cursor.execute(exec_string) return Trade.from_tuple(table_name, cursor.fetchone())
def _search_for_quantity_in_price_level_total(self, tick_entry, quantity_to_trade, order): if tick_entry.quantity <= Quantity(0): return quantity_to_trade, [] trading_quantity = quantity_to_trade quantity_to_trade = Quantity(0) self._logger.debug("Match with the id (%s) was found for order (%s). Price: %i, Quantity: %i)", str(tick_entry.order_id), str(order.order_id), int(tick_entry.price), int(trading_quantity)) reserved = order.reserve_quantity_for_tick(tick_entry.tick.order_id, trading_quantity) if not reserved: # Error happened self._logger.warn("Something went wrong") return self._search_for_quantity_in_price_level(tick_entry.next_tick(), quantity_to_trade, order) proposed_trades = [Trade.propose( self.order_book.message_repository.next_identity(), order.order_id, tick_entry.order_id, tick_entry.price, trading_quantity, Timestamp.now() )] return quantity_to_trade, proposed_trades
def lookup(table_name, index): dbm = DBManager.get_instance() cursor = dbm.get_cursor() exec_string = "SELECT * FROM '{tn}' WHERE id = {i}".format( tn=table_name, i=index) cursor.execute(exec_string) return Trade.from_tuple(table_name, cursor.fetchone())
def process_message(self, values: List): if len(values) == 0: # empty line. ignore return None action_str = values.pop(0) try: action = ActionEnum[action_str] # Trade if action == ActionEnum.T: self.process_trade(Trade.parse(values)) # Order else: self._report_any_expected_trades_as_missing() order = Order.from_list(values) if action == ActionEnum.A: self.process_add_order(order) elif action == ActionEnum.M: self.process_modify_order(order) else: # action == ActionEnum.X: self.process_remove_order(order) return action except KeyError: self._errors.add( ErrorEnum.CorruptedMessage, self._format_error(action_str, values, "Invalid Action")) except CorruptedMessageError as er: self._errors.add(ErrorEnum.CorruptedMessage, self._format_error(action_str, values, er)) except InvalidValueError as er: self._errors.add(ErrorEnum.InvalidValue, self._format_error(action_str, values, er)) return None
def confirmSettle(self): rowIndex = self.currentIndex().row() tradeID = self.model().index(rowIndex, 14).data().toString() trd = Trade.fromDB(tradeID) if trd: trd.settle(self.user.id) else: QtGui.QMessageBox.warning(self, u'错误', u'无法从数据库读取该笔交易')
def test_run_trade_wexpire(pair, start, type, SL, TP, entry, entered): ''' This test checks the run_trade method with the 'expires' parameter ''' td = Trade( start=start, entry=entry, SL=SL, TP=TP, pair=pair, type=type, timeframe="D", strat="counter_b2", id="test") td.run_trade(expires=2) assert td.entered == entered
def win_rate(self, strats): ''' Calculate win rate and pips balance for this TradeJournal. If outcome attrb is not defined then it will invoke the run_trade method on each particular trade Parameters ---------- strats : str Comma-separated list of strategies to analyse: i.e. counter,counter_b1 Returns ------- int : number of successes int : number of failures pips : pips balance in this TradeList ''' strat_l = strats.split(",") number_s = number_f = tot_pips = 0 for index, row in self.df.iterrows(): pair = row['id'].split(" ")[0] args = {'pair': pair} for c in row.keys(): args[c] = row[c] t = Trade(**args) if t.strat not in strat_l: continue if not hasattr(t, 'outcome') or math.isnan(t.outcome): t.run_trade(expires=1) if t.outcome == 'success': number_s += 1 elif t.outcome == 'failure': number_f += 1 tot_pips += t.pips tot_pips = round(tot_pips, 2) tot_trades = number_s+number_f perc_wins = round(number_s*100/tot_trades, 2) perc_losses = round(number_f*100/tot_trades, 2) print("Tot number of trades: {0}\n-------------".format(tot_trades)) print("Win trades: {0}; Loss trades: {1}".format(number_s, number_f)) print("% win trades: {0}; % loss trades: {1}".format(perc_wins, perc_losses)) print("Pips balance: {0}".format(tot_pips)) return number_s, number_f, tot_pips
def test_run_trade_4hrs(pair, start, type, SL, TP, entry, outcome): ''' This test checks the run_trade method with the 'expires' parameter ''' td = Trade( start=start, entry=entry, SL=SL, TP=TP, pair=pair, type=type, timeframe="H4", strat="counter_b2", id="test") td.run_trade() assert td.outcome == outcome
def generate_trade_record(self): trades = pd.DataFrame(Trade.to_dict()) trades['duration'] = trades['close_date'] - trades['open_date'] trades['returns'] = (trades['close_price'] / trades['open_price']) - 1 trades['win_trades'] = trades['returns'] > 0 trades['loss_trades'] = trades['returns'] <= 0 self.trades = trades
def main(amountPercentage, altCoin, profitPercent, lossPercent): # SUPPORT BTC ONLY defaultCoin = "BTC" # Check BTC Balance balance = Check.CheckBalance(defaultCoin) exchange = altCoin + defaultCoin # Need to convert to count the no. of quantity to BUY since its required for the API estimatedquantity = Cal.ConvertToQuantityBaseOnMarket( exchange, balance, amountPercentage) quantity, boughtPrice = Trade.MarketBuy(exchange, estimatedquantity) Trade.ZemusMethod(exchange, boughtPrice, profitPercent, lossPercent, quantity)
def create_trade(self, p1: Player, p2_name: str, card_ids: List[str], wants: List[str]): tcs: List[TradingCard] = self.ids_to_tcs(p1, card_ids) new_trades: List[Trade] = [] p2: Player = util.shrink([player for player in self.players if player.name == p2_name]) if not p2: return util.error("Player chosen is not in game") new_trades += [Trade(p1, p2, tcs, wants)] self.trades += new_trades return util.success('Successfully created trade')
def prepare_trade(tb_obj, type, SL, ic, harea_sel, delta, add_pips): ''' Prepare a Trade object and check if it is taken Parameters ---------- tb_obj : TradeBot object type : str, Type of trade. 'short' or 'long' SL : float, Adjusted (by '__get_trade_type') SL price ic : Candle object Indecision candle for this trade harea_sel : HArea of this trade delta : Timedelta object corresponding to the time that needs to be increased add_pips : Number of pips above/below SL and entry price to consider for recalculating the SL and entry. Default : None Returns ------- Trade object ''' startO = ic.time + delta if type == 'short': # entry price will be the low of IC entry_p = getattr(ic, "low{0}".format(CONFIG.get('general', 'bit'))) if add_pips is not None: SL = round(add_pips2price(tb_obj.pair, SL, add_pips), 4) entry_p = round(substract_pips2price(tb_obj.pair, entry_p, add_pips), 4) elif type == 'long': # entry price will be the high of IC entry_p = getattr(ic, "high{0}".format(CONFIG.get('general', 'bit'))) if add_pips is not None: entry_p = add_pips2price(tb_obj.pair, entry_p, add_pips) SL = substract_pips2price(tb_obj.pair, SL, add_pips) startO = ic.time+delta t = Trade( id='{0}.bot'.format(tb_obj.pair), start=startO.strftime('%Y-%m-%d %H:%M:%S'), pair=tb_obj.pair, timeframe=tb_obj.timeframe, type=type, entry=entry_p, SR=harea_sel.price, SL=SL, RR=CONFIG.getfloat('trade_bot', 'RR'), strat='counter') return t
class TestTrade(TestCase): def setUp(self): self.exchange = Trade() def test_GetAccount(self): r = self.exchange.GetAccount() print() def test_GetTicker(self): r = self.exchange.GetTicker() print() def test_Buy(self): r = self.exchange.Buy(10000) print() def test_Sell(self): r = self.exchange.Sell(100000) print()
def confirmExpSettle(self): rowIndex = self.currentIndex().row() tradeID = self.model().index(rowIndex, 14).data().toString() trd = Trade.fromDB(tradeID) if trd: if self.asOfDate != trd.maturityDate: QtGui.QMessageBox.warning(self, u'注意', u'当前日期与预期到期交割日不同,将按预期到期日交割') trd.expsettle(self.user.id) else: QtGui.QMessageBox.warning(self, u'错误', u'无法从数据库读取该笔交易')
def test_run_trade(pair, start, type, SL, TP, entry, outcome): ''' This test checks the progression of the Trade and checks if the outcome attribute is correctly defined. ''' td = Trade( start=start, entry=entry, SL=SL, TP=TP, pair=pair, type=type, timeframe="D", strat="counter_b2", id="test") td.run_trade() assert td.outcome == outcome
def sell_stock(self, stock, quantity, price, timestamp=None): """ records a sell event for a given stock if no Timestamp is provided it uses the current timestamp returns the Trade """ return self._record_trade( stock, Trade(quantity, TRADE_TYPE.SELL, price, timestamp=(timestamp or dt.now())))
def trade_handler(self, resp): symbol = resp['trade']['symbol'] if resp['trade']['symbol'] not in self.trades.keys(): t = Trade(resp['trade']) else: t = Trade(self.trades[symbol].merge(resp['trade'])) if t.is_complete() is False: trade_data = self.tk.get_quotes([symbol]) t.merge(trade_data) oid = t.save() self.trades[symbol] = t self.conn.send(TradeEvent(name='new_trade', object_id=oid, symbol=symbol))
from pymongo import MongoClient from trade import Trade from trades_repository import TradesRepository trade = Trade(0) trade.setTrade(500) repo = TradesRepository("test", "testData") repo.upsert(trade)
def handleAction(self, playerName, action, options): if self.getCurrentTurnPlayerName() != playerName: print "Not your turn! Player's " + str(self.getTurns()/2) + " turn." return False self.affectedPlayers = [] player = self.getPlayerWithName(playerName) if player == None: print "Cannot find player!" return False self.jsonResponse = None if action is Action.TradeRequest: print "trade offer" #options contains targetPlayerNames, resourceOffer, resourceRequest targetPlayerNames = options["targetPlayerNames"] resourcesOffer = options["offer"] resourcesRequest = options["want"] if not targetPlayerNames or not resourcesOffer or not resourcesRequest: return False targetPlayers = [] for name in targetPlayerNames: targetPlayer = self.getPlayerWithName(name) targetPlayers.append(targetPlayer) if self.logicHandler.ingredient_suffice_to_trade(player, resourcesOffer): self.currentTrade = Trade(player, resourcesOffer, resourcesRequest, targetPlayers) self.affectedPlayers.append(player) for playerName in targetPlayerNames: targetPlayer = self.getPlayerWithName(playerName) self.affectedPlayers.append(targetPlayer) makeTradeTemplateJson(self.currentTrade) return True else: return False if action is Action.TradeAccept: print "Trade accept" #options contains tradeId tradeId = options["tradeId"] if not self.isTradeValidWithIdAndName(tradeId, player.get_name()): return False if self.logicHandler.accept_trade(player, self.currentTrade): self.currentTrade.set_player_responded(player.get_name()) self.affectedPlayers.append(player) #player who accept the trade self.affectedPlayers.append(self.currentTrade.get_initiator()) self.makeUpdateTemplateJson() return True else: return False elif action is Action.TradeDeny: print "trade deny" #options contains tradeId tradeId = options["tradeId"] if not self.isTradeValidWithIdAndName(tradeId, player.get_name()): return False self.currentTrade.set_player_responded(player.get_name()) return True elif action is Action.TradeWithBank: print "trade with bank" #options contains resourcesOffer, resourcesRequest bankMultiplier = self.eventHandler.getBankMultiplier() if self.logicHandler.trade_with_bank(player, options["offer"], options["want"], bankMultiplier): self.affectedPlayers.append(player) self.makeUpdateTemplateJson() return True else: return False elif action is Action.Build or action is Action.UpgradeResourceGenerator: print "Build or upgrade resouce generator" #options contains generatorName if self.logicHandler.build(player, options["target"]): self.affectedPlayers.append(player) self.makeUpdateTemplateJson() return True else: return False elif action is Action.Gather: print "gather" multipliers = self.eventHandler.getGeneratorMultipliers() if self.logicHandler.gather(player, multipliers): self.affectedPlayers.append(player) self.makeUpdateTemplateJson() return True else: return False elif action is Action.Destroy: #options contains targetPlayerName , buildingName print "destroy" targetPlayer = self.getPlayerWithName(options["to"]) if self.logicHandler.destroy(player, targetPlayer, options["target"]): self.affectedPlayers.append(player) self.affectedPlayers.append(targetPlayer) self.makeUpdateTemplateJson() return True else: return False elif action is Action.UpgradeResource: print "upgrade resource" #options contains resourceType if self.logicHandler.upgrade_resource(player, options["target"]): self.affectedPlayers.append(player) self.makeUpdateTemplateJson() return True else: return False else: print("error action") return False
class Game(object): def __init__(self, playerNames): self.logicHandler = LogicHandler() self.eventHandler = EventHandler() self.players = [] self.turns = 0 self.jsonResponse = {} for playerName in playerNames: objective = self.logicHandler.get_random_objective() self.players.append(Player(playerName, objective)) def handleAction(self, playerName, action, options): if self.getCurrentTurnPlayerName() != playerName: print "Not your turn! Player's " + str(self.getTurns()/2) + " turn." return False self.affectedPlayers = [] player = self.getPlayerWithName(playerName) if player == None: print "Cannot find player!" return False self.jsonResponse = None if action is Action.TradeRequest: print "trade offer" #options contains targetPlayerNames, resourceOffer, resourceRequest targetPlayerNames = options["targetPlayerNames"] resourcesOffer = options["offer"] resourcesRequest = options["want"] if not targetPlayerNames or not resourcesOffer or not resourcesRequest: return False targetPlayers = [] for name in targetPlayerNames: targetPlayer = self.getPlayerWithName(name) targetPlayers.append(targetPlayer) if self.logicHandler.ingredient_suffice_to_trade(player, resourcesOffer): self.currentTrade = Trade(player, resourcesOffer, resourcesRequest, targetPlayers) self.affectedPlayers.append(player) for playerName in targetPlayerNames: targetPlayer = self.getPlayerWithName(playerName) self.affectedPlayers.append(targetPlayer) makeTradeTemplateJson(self.currentTrade) return True else: return False if action is Action.TradeAccept: print "Trade accept" #options contains tradeId tradeId = options["tradeId"] if not self.isTradeValidWithIdAndName(tradeId, player.get_name()): return False if self.logicHandler.accept_trade(player, self.currentTrade): self.currentTrade.set_player_responded(player.get_name()) self.affectedPlayers.append(player) #player who accept the trade self.affectedPlayers.append(self.currentTrade.get_initiator()) self.makeUpdateTemplateJson() return True else: return False elif action is Action.TradeDeny: print "trade deny" #options contains tradeId tradeId = options["tradeId"] if not self.isTradeValidWithIdAndName(tradeId, player.get_name()): return False self.currentTrade.set_player_responded(player.get_name()) return True elif action is Action.TradeWithBank: print "trade with bank" #options contains resourcesOffer, resourcesRequest bankMultiplier = self.eventHandler.getBankMultiplier() if self.logicHandler.trade_with_bank(player, options["offer"], options["want"], bankMultiplier): self.affectedPlayers.append(player) self.makeUpdateTemplateJson() return True else: return False elif action is Action.Build or action is Action.UpgradeResourceGenerator: print "Build or upgrade resouce generator" #options contains generatorName if self.logicHandler.build(player, options["target"]): self.affectedPlayers.append(player) self.makeUpdateTemplateJson() return True else: return False elif action is Action.Gather: print "gather" multipliers = self.eventHandler.getGeneratorMultipliers() if self.logicHandler.gather(player, multipliers): self.affectedPlayers.append(player) self.makeUpdateTemplateJson() return True else: return False elif action is Action.Destroy: #options contains targetPlayerName , buildingName print "destroy" targetPlayer = self.getPlayerWithName(options["to"]) if self.logicHandler.destroy(player, targetPlayer, options["target"]): self.affectedPlayers.append(player) self.affectedPlayers.append(targetPlayer) self.makeUpdateTemplateJson() return True else: return False elif action is Action.UpgradeResource: print "upgrade resource" #options contains resourceType if self.logicHandler.upgrade_resource(player, options["target"]): self.affectedPlayers.append(player) self.makeUpdateTemplateJson() return True else: return False else: print("error action") return False def isTradeValidWithIdAndName(self, tradeId, playerName): if not tradeId or tradeId != self.currentTrade.get_id() or \ playerName not in self.currentTrade.get_target_players_name(): return False if self.currentTrade.get_is_trade_over(): print("trade is over") return False return True def updateEventAndGetUpcomingEvents(self): self.eventHandler.randomUpcomingEvent() currentEvents = self.eventHandler.getUpcomingEvents() def getPlayerWithName(self, name): for player in self.players: if player.get_name() == name: return player print "player not found" return None def playerLeft(self, player_name): for player in self.players: if (player_name == player.get_name()): self.players.remove(player) break; def getAffectedPlayersSummaries(self): affectedPlayerSummaries = {} for player in self.affectedPlayers: playerSummary = {} resources = player.get_resources() for res, count in resources.items(): playerSummary[res.name] = count generator = player.get_generators() for gen, count in generator.items(): playerSummary[gen.name] = count affectedPlayerSummaries[player.get_name()] = playerSummary return affectedPlayerSummaries def getAllPlayersSummaries(self): allPlayerSummaries = {} for player in self.players: playerSummary = {} resources = player.get_resources() for res, count in resources.items(): playerSummary[res.name] = count generator = player.get_generators() for gen, count in generator.items(): playerSummary[gen.name] = count allPlayerSummaries[player.get_name()] = playerSummary return allPlayerSummaries def getGeneratorsAndBankMultipliers(self): multipliers = {} for key, mutliplier in self.eventHandler.getGeneratorMultipliers.items(): mutliplier[key.name] = multipliers multipliers["bank"] = self.eventHandler.getBankMultiplier() return multipliers def getTradeId(self): return self.currentTrade.get_id() def getIsTradeOver(self): return self.currentTrade.get_is_trade_over() def getTurns(self): return self.turns def increaseTurns(self): self.turns += 1 def setTurns(self, turns): self.turns = turns def getCurrentTurnPlayerName(self): return self.players[(self.getTurns()/2)].get_name() def makeUpdateTemplateJson(self): json = {} json['action'] = "Update" json['update_res'] = self.getAffectedPlayersSummaries() self.jsonResponse = json def makeTradeTemplateJson(self, trade): json = {} json['action'] = "TradeRequest" json['from'] = trade.get_initiator() json['to'] = trade.get_target_players_name() json['want'] = trade.get_resources_request() json['offer'] = trade.get_resources_offer() json['tid'] = trade.get_id() self.jsonResponse = json def getJsonResponse(self): return self.jsonResponse
def main(): account = 'CLS8002286' venue = 'VXEX' stock = 'KCYE' price = 0 qty = 0 direction = OrderDirection.buy orderType = OrderType.limit waitTime = 1 oldPrice = 0 trade = Trade(account, venue, stock, price, qty, direction, orderType) quote = Quote(venue, stock) # buy low, sell high # track stocks owned, and exposure (value per last trade) while (True): # get the spread quote.refresh() quote.prt() # work the spread trade.orderType = OrderType.limit if (quote.bid is not None and quote.ask is not None): # buy at the bid + 1 trade.direction = OrderDirection.buy trade.price = quote.bid + 5 trade.qty = quote.bidSize trade.prt() trade.execute() # sell at the ask - 1 trade.direction = OrderDirection.sell trade.price = quote.ask - 5 trade.size = quote.askSize trade.prt() trade.execute() time.sleep(2)