def _from_trades_row_to_trade(row): """ Convert a row of trades into a trade object """ ## IB has negative for buys, and positive for sales (i.e. cashflow method) value = float(row['Notional Value'].replace(',', '')) quantity = float(row.Quantity.replace(',', '')) ## Note that taxes and commissions are reported as negative (cashflow) ## Value is negative for buys and positive for sells, which is fine ## quantities are already signed this_trade = Trade(Code=row.Symbol, Currency=row.Currency, Price=float(row.Price.replace(',', '')), Tax=abs(float(row.Tax.replace(',', ''))), Commission=abs(float(row.Comm.replace(',', ''))), Date=_parse_trade_date(row['Trade Date']), SignQuantity=quantity, Quantity=abs(quantity), Value=value, AssetClass=row.AssetClass) return this_trade
def testAddingTrade(self, stock_symbol_, timestamp_, quantity_, buy_or_sell_, trade_price_): t = Trade(stock_symbol_, timestamp_, quantity_, buy_or_sell_, trade_price_) tm = TradeManager() tm.add(t) self.assertEqual(len(tm), 1)
def fill_order(self, trade: Trade, current_price: float) -> Trade: amount_slippage = np.random.uniform( 0, self.max_amount_slippage_percent / 100) price_slippage = np.random.uniform( 0, self.max_price_slippage_percent / 100) fill_amount = trade.amount * (1 - amount_slippage) fill_price = current_price if trade.trade_type is TradeType.MARKET_BUY: fill_price = current_price * (1 + price_slippage) elif trade.trade_type is TradeType.LIMIT_BUY: fill_price = current_price * (1 + price_slippage) if fill_price > trade.price: fill_price = trade.price fill_amount *= trade.price / fill_price elif trade.trade_type is TradeType.MARKET_SELL: fill_price = current_price * (1 - price_slippage) elif trade.trade_type is TradeType.LIMIT_SELL: fill_price = current_price * (1 - price_slippage) if fill_price < trade.price: fill_price = trade.price fill_amount *= fill_price / trade.price return Trade(trade.symbol, trade.trade_type, amount=fill_amount, price=fill_price)
def docMappings(self, connection, indexName=DEFAULT_INDEX): try: connection.indices.put_mapping(index=indexName, doc_type="orderbook", body=Orderbook().orderbookMapping) connection.indices.put_mapping(index=indexName, doc_type="ticker", body=Ticker().tickerMapping) connection.indices.put_mapping(index=indexName, doc_type="completed_trades", body=Trade().completedTradeMapping) connection.indices.put_mapping(index=indexName, doc_type="future_ticker", body=Ticker().futureTickerMapping) connection.indices.put_mapping(index=indexName, doc_type="future_price_index", body=FutureIndex().futurePriceIndexMapping) connection.indices.put_mapping(index=indexName, doc_type="kline_candles", body=KlineCandle().klineMapping) except: raise pass
def create_trade(self, trade_id: str, enter_or_exit: str, long_or_short: str, order_type: str = 'mkt', price: float = 0.00, stop_limit_price: float = 0.00): # initilize trade trade = Trade() trade.new_trade(trade_id=trade_id, order_type=order_type, enter_or_exit=enter_or_exit, long_or_short=long_or_short, price=price, stop_limit_price=stop_limit_price) self.trades[trade_id] = trade return trade
def reset(self) -> pd.DataFrame: """Resets the state of the environment and returns an initial observation. Returns: observation: the initial observation. """ self._action_strategy.reset() self._reward_strategy.reset() self._exchange.reset() self._current_step = 0 return self._next_observation(Trade('N/A', 'hold', 0, 0))
def from_csv_row_to_trade(row, useassetclass): """ Taxes and commissions are positive Quantity is unsigned """ this_trade=Trade(Code=row.Company, Currency=row.Currency, Price=_resolvetype(row.Price), Tax=_resolvetype(row.Tax), Commission=_resolvetype(row.Charges), BS=_resolveBS(row["B/S"]), Date=datetime.datetime.strptime(row['Date'], "%d/%m/%Y"), Quantity=abs(_resolvetype(row.Shares)), AssetClass=useassetclass) return this_trade
def get_trade(self, action: TradeActionUnion) -> Trade: action_type, trade_amount = action trade_type = TradeType(int(action_type * len(TradeType))) current_price = self._exchange.current_price(symbol=self.instrument_symbol) base_precision = self._exchange.base_precision instrument_precision = self._exchange.instrument_precision amount = self._exchange.balance_of_instrument(self.instrument_symbol) price = current_price if trade_type is TradeType.MARKET_BUY or trade_type is TradeType.LIMIT_BUY: price_adjustment = 1 + (self.max_allowed_slippage_percent / 100) price = round(current_price * price_adjustment, base_precision) amount = round(self._exchange.balance * 0.99 * trade_amount / price, instrument_precision) elif trade_type is TradeType.MARKET_SELL or trade_type is TradeType.LIMIT_SELL: price_adjustment = 1 - (self.max_allowed_slippage_percent / 100) price = round(current_price * price_adjustment, base_precision) amount_held = self._exchange.portfolio.get(self.instrument_symbol, 0) amount = round(amount_held * trade_amount, instrument_precision) return Trade(self.instrument_symbol, trade_type, amount, price)
def simulation(): ''' It shows - at each trade - DIVIDEND YIELD, P/E RATIO values - last 15 secs trades - Valume Weighted Stock Price - all trades - GBCE ALL Share Index ''' trade_manager = TradeManager() list_of_trades = generate_trades() for trade in list_of_trades: print('TRADE: {0}'.format(trade)) stock = _stock_manager[trade[0]] print( 'STOCKS -- SYMBOL: {0}, MARKET PRICE: {1}, DIVIDEND YEALD: {2}, P/E RATIO: {3}' .format(trade[0], trade[4], stock.dividend_yield(trade[4]), stock.pe_ratio(trade[4]))) trade_manager.add(Trade(*trade)) print('TRADES -- Volume Weighted Stock Price in the last 15 seconds: {0}'. format(trade_manager.volume_weighted_stock_price(15))) print('TRADES -- GBCE All Share Index: {0}'.format( trade_manager.gbce_all_share_index()))
txid = fund_sell_contract(trade) print("Sent") create_buy_p2sh(trade, secret, buy_locktime) print_trade('seller') if __name__ == '__main__': print("ZEC <-> BTC XCAT (Cross-Chain Atomic Transactions)") print("=" * 50) trade = get_trade() if trade == None: htlcTrade = Trade() print("New empty trade") else: buyContract = Contract(trade['buy']) sellContract = Contract(trade['sell']) htlcTrade = Trade(buyContract=buyContract, sellContract=sellContract) try: if sys.argv[1] == 'new': erase_trade() role = 'seller' htlcTrade = Trade() print("Creating new XCAT transaction...") else: role = sys.argv[1] print("Your role in demo:", role)
def consumer(self, marketData): connection = elasticsearch.Elasticsearch(self.esHost) self.ensure(connection) self.docMappings(connection) dataSet = json.loads(marketData) item = {} for infoPoint in dataSet: try: channel = str(infoPoint["channel"]) regex = "ok_sub_(spotusd|futureusd)_(b|l)tc_(.[A-Za-z0-9_]+)" search = re.search(regex, channel) if search.group(1) == "futureusd": isFuture = True else: isFuture = False currencyPair = str(search.group(2)) + "tc_usd" self.count = self.count + 1 if self.count % 100 == 0: print ("PROCESSED " + str(self.count) + " DATA POINTS SO FAR...") if search.group(3) == "index": myindex = FutureIndex() dto = myindex.getFutureIndexDto(infoPoint, currencyPair) dto["exchange"] = "OKCOIN" self.postDto(dto, connection, "future_price_index") elif "depth" in channel: mybook = Orderbook() dto = mybook.getDepthDtoList(infoPoint, currencyPair, isFuture) for item in dto: item["websocket_name"] = channel item["is_future"] = isFuture if isFuture == True: check = re.search("depth_(this_week|next_week|quarter)_(20|60)", search.group(3).strip()) item["contract_type"] = str(check.group(1)) item["depth"] = str(check.group(2)) else: item["contract_type"] = "spot" depthSearch = re.search("depth_(20|60)", search.group(3).strip()) item["depth"] = depthSearch.group(1) item["exchange"] = "OKCOIN" self.postDto(item, connection, "orderbook") elif "ticker" in channel and "data" in infoPoint: myticker = Ticker() if isFuture == False: dto = myticker.getTickerDto(infoPoint, currencyPair) self.postDto(dto, connection, "ticker") elif isFuture == True: dto = myticker.getFutureTickerDto(infoPoint, channel, currencyPair) dto["exchange"] = "OKCOIN" self.postDto(dto, connection, "future_ticker") elif "trade" in channel: mytrade = Trade() if "data" in infoPoint: dtoList = mytrade.getCompletedTradeDtoList(infoPoint, currencyPair) for item in dtoList: item["is_future"] = "futureusd" in channel item["websocket_name"] = channel item["exchange"] = "OKCOIN" self.postDto(item, connection, "completed_trades") elif "kline" in channel: myklein = KlineCandle() if "data" in infoPoint: if len(infoPoint["data"]) > 1: for klineData in infoPoint["data"]: if type(klineData) is list: klineDto = myklein.getKlineDto(klineData, currencyPair, channel) klineDto["exchange"] = "OKCOIN" klineDto["is_future"] = isFuture klineDto["websocket_name"] = channel else: klineDto = myklein.getKlineDto(infoPoint["data"], currencyPair, channel) self.postDto(klineDto, connection, "kline_candles") except: raise
def testInvalidTrade2(self, stock_symbol_, quantity_, buy_or_sell_, trade_price_): with self.assertRaises(TradeException): t = Trade.create_trade(stock_symbol_, quantity_, buy_or_sell_, trade_price_)
def testCreateATrade2(self, stock_symbol_, quantity_, buy_or_sell_, trade_price_): t = Trade.create_trade(stock_symbol_, quantity_, buy_or_sell_, trade_price_) self.assertTrue(t.valid())