creates trade_count trades for each sid in sids list.
    first trade will be on sim_params.start_session, and daily
    thereafter for each sid. Thus, two sids should result in two trades per
    day.
555510
def create_daily_trade_source(sids,
                              sim_params,
                              asset_finder,
                              trading_calendar):
    
    return create_trade_source(
        sids,
        timedelta(days=1),
        sim_params,
        asset_finder,
        trading_calendar=trading_calendar,
    )
1171004
def register_trading_control(self, control):
        
        if self.initialized:
            raise RegisterTradingControlPostInit()
        self.trading_controls.append(control)
1012518
def trade(self, trade_id, trade_price, trade_amount, trade_time):
        
        if self.status in [ORDER_STATUS.SUCCESS_PART, ORDER_STATUS.QUEUED]:
            trade_amount = int(trade_amount)
            trade_id = str(trade_id)

            if trade_amount < 1:

                self._status = ORDER_STATUS.NEXT
            else:
                if trade_id not in self.trade_id:
                    trade_price = float(trade_price)

                    trade_time = str(trade_time)

                    self.trade_id.append(trade_id)
                    self.trade_price = (
                        self.trade_price * self.trade_amount +
                        trade_price * trade_amount
                    ) / (
                        self.trade_amount + trade_amount
                    )
                    self.trade_amount += trade_amount
                    self.trade_time.append(trade_time)
                    self.callback(
                        self.code,
                        trade_id,
                        self.order_id,
                        self.realorder_id,
                        trade_price,
                        trade_amount,
                        self.towards,
                        trade_time
                    )
                else:
                    pass
        else:
            raise RuntimeError(
                'ORDER STATUS {} CANNNOT TRADE'.format(self.status)
            )
728771
public static function build_ohlcv ($trades, $timeframe = '1m', $since = PHP_INT_MIN, $limits = PHP_INT_MAX) {
        if (empty ($trades) || !is_array ($trades)) {
            return array ();
        }
        if (!is_numeric ($since)) {
            $since = PHP_INT_MIN;
        }
        if (!is_numeric ($limits)) {
            $limits = PHP_INT_MAX;
        }
        $ms = static::parse_timeframe ($timeframe) * 1000;
        $ohlcvs = array ();
        list(/* $timestamp */, /* $open */, $high, $low, $close, $volume) = array (0, 1, 2, 3, 4, 5);
        for ($i = 0; $i < min (count($trades), $limits); $i++) {
            $trade = $trades[$i];
            if ($trade['timestamp'] < $since)
                continue;
            $openingTime = floor ($trade['timestamp'] / $ms) * $ms; // shift to the edge of m/h/d (but not M)
            $j = count($ohlcvs);

            if ($j == 0 || $openingTime >= $ohlcvs[$j-1][0] + $ms) {
                // moved to a new timeframe -> create a new candle from opening trade
                $ohlcvs[] = array (
                    $openingTime,
                    $trade['price'],
                    $trade['price'],
                    $trade['price'],
                    $trade['price'],
                    $trade['amount']
                );
            } else {
                // still processing the same timeframe -> update opening trade
                $ohlcvs[$j-1][$high] = max ($ohlcvs[$j-1][$high], $trade['price']);
                $ohlcvs[$j-1][$low] = min ($ohlcvs[$j-1][$low], $trade['price']);
                $ohlcvs[$j-1][$close] = $trade['price'];
                $ohlcvs[$j-1][$volume] += $trade['amount'];
            }
        }
        return $ohlcvs;
    }
367263
def trade_signals_handler(self, signals):
        '''
        
        '''
        alloc = {}

        if signals['buy'] or signals['sell']:
            # Compute the optimal portfolio allocation,
            # Using user defined function
            try:
                alloc, e_ret, e_risk = self.optimize(
                    self.date, signals['buy'], signals['sell'],
                    self._optimizer_parameters)
            except Exception, error:
                raise PortfolioOptimizationFailed(
                    reason=error, date=self.date, data=signals)
        return _remove_useless_orders(alloc)
1063733
def new_session(self):
        """"""
        body = yield from self._fetch_json(URL_LOGIN, self._new_session_data)
        self.sma_sid = jmespath.search('result.sid', body)
        if self.sma_sid:
            return True

        msg = 'Could not start session, %s, got {}'.format(body)

        if body.get('err'):
            if body.get('err') == 503:
                _LOGGER.error("Max amount of sessions reached")
            else:
                _LOGGER.error(msg, body.get('err'))
        else:
            _LOGGER.error(msg, "Session ID expected [result.sid]")
        return False
10473
def trade(self):
        

        return self.history_table.pivot_table(
            index=['datetime',
                   'account_cookie'],
            columns='code',
            values='amount',
            aggfunc=np.sum
        ).fillna(0).sort_index()
263605
def trades_get(self, **kwargs):
        ''''''
        request = TOPRequest('taobao.increment.trades.get')
        for k, v in kwargs.iteritems():
            if k not in ('status', 'nick', 'type', 'start_modified', 'end_modified', 'page_no', 'page_size') and v==None: continue
            request[k] = v
        self.create(self.execute(request), fields=['notify_trades', 'total_results'], models={'notify_trades':NotifyTrade})
        return self.notify_trades
9544
def newlogins(sessions):
    
    if not sessions:
        return [], []
    users = {}
    dates = {}

    for session in sessions:
        user = session.user
        # time value is discarded to aggregate on days only
        date = session.started_at.strftime("%Y/%m/%d")
        # keep the info only it's the first time we encounter a user
        if user not in users:
            users[user] = date
            # build the list of users on a given day
            if date not in dates:
                dates[date] = [user]
            else:
                dates[date].append(user)

    data = []
    total = []
    previous = 0
    for date in sorted(dates.keys()):
        # print u"{} : {}".format(date, len(dates[date]))
        date_epoch = unix_time_millis(datetime.strptime(date, "%Y/%m/%d"))
        data.append({"x": date_epoch, "y": len(dates[date])})
        previous += len(dates[date])
        total.append({"x": date_epoch, "y": previous})

    return data, total
204897
public static List<UserTrade> adaptUserTrades(
      List<CurrencyPair> currencyPairList, List<LykkeOrder> tradeHistoryList) throws IOException {
    List<UserTrade> userTrades = new ArrayList<>();

    for (LykkeOrder lykkeTradeHistory : tradeHistoryList) {
      userTrades.add(adaptUserTrade(currencyPairList, lykkeTradeHistory));
    }
    return userTrades;
  }
780784
static int countInPeriod(Weekday dow, Weekday dow0, int nDays) {
        // Two cases
        //    (1a) dow >= dow0: count === (nDays - (dow - dow0)) / 7
        //    (1b) dow < dow0:  count === (nDays - (7 - dow0 - dow)) / 7
        if (dow.javaDayNum >= dow0.javaDayNum) {
            return 1 + ((nDays - (dow.javaDayNum - dow0.javaDayNum) - 1) / 7);
        } else {
            return 1 + ((nDays - (7 - (dow0.javaDayNum - dow.javaDayNum)) - 1) / 7);
        }
    }
1092195
def trade(args):
    """"""
    print args
    print vars(args)['funds']
    print args.funds
    portfolio = { '$CASH': args.funds }
    print portfolio
    csvreader = csv.reader(args.infile, dialect='excel', quoting=csv.QUOTE_MINIMAL)
    csvwriter = csv.writer(args.outfile, dialect='excel', quoting=csv.QUOTE_MINIMAL)
    detailed = not args.simple
    history = []
    portfolio_history = []

    #trading_days = du.getNYSEdays(datetime.datetime(2010,01,01), datetime.datetime(2012,01,01), datetime.timedelta(hours=16))
    for row in csvreader:
        # print '-'*30 + ' CSV Row ' + '-'*30
        # print ', '.join(row)
        trade_date = datetime.datetime(*[int(i) for i in (row[:3] + [16])])

        if history:
            last_date = datetime.datetime(*(history[-1][:3] + [16])) + datetime.timedelta(days=1)
            # print (date.date() - last_date).days
            while (trade_date - last_date).days > 0:
                print 'Filling in the blanks for {0}'.format(last_date)
                value = portfolio_value(portfolio, last_date, price='close')
                print '   the portfolio value on that date is: {0}'.format(value)
                assert(value != None)
                # NaN for porfolio value indicates a non-trading day
                if not np.isnan(value):
                    history += [[last_date.year, last_date.month, last_date.day] 
                                + (["$CASH", "0.0", "0.0"] if args.trades else [])
                                + ([json.dumps(portfolio)] if detailed else []) + [value]]
                    portfolio_history += [datetime.datetime(last_date.year, last_date.month, last_date.day, 16), portfolio]
                    csvwriter.writerow(history[-1])
                last_date += datetime.timedelta(days=1)
    
        trade_symbol = row[3]
        trade_shares = float(row[5])
        trade_sign = 1 - 2 * int(row[4].strip().upper()[0]=='S')
        # If this the first row in the CSV and the symbol is $CASH then it represents an initial deposit (Sell) or withdrawal (Buy) of cash
        # otherwise se need to add or deduct whatever security was bought or sold.
        # if not (trade_symbol == '$CASH') or history:
        portfolio[trade_symbol] = portfolio.get(trade_symbol, 0) + trade_sign * trade_shares
        trade_price = get_price(symbol=trade_symbol, date=trade_date, price='close')
        while trade_price == None or np.isnan(trade_price) or float(trade_price) == float('nan'):
            trade_date += datetime.timedelta(days=1)
            trade_price = get_price(symbol=trade_symbol, date=trade_date, price='close')
        #print trade_date, trade_symbol, trade_sign, trade_shares, trade_price
        if trade_price and trade_shares and trade_sign in (-1, 1):
            print 'spending cash: {0}'.format(trade_sign * trade_shares * trade_price)
            portfolio['$CASH'] = portfolio.get('$CASH',0.) - trade_sign * trade_shares * trade_price
        else:
            print 'ERROR: bad price, sign, shares: ', trade_price, trade_sign, trade_shares
        history += [[trade_date.year, trade_date.month, trade_date.day, trade_symbol, trade_sign, trade_shares] + ([json.dumps(portfolio)] if detailed else []) + [portfolio_value(portfolio, trade_date, price='close')]]
        csvwriter.writerow(history[-1])
    return metrics(history)
962271
def _calc_daystamps(self, st_time, end_time):
        
        start_doy = sum(self._num_of_days_each_month[:st_time.month-1]) + st_time.day
        end_doy = sum(self._num_of_days_each_month[:end_time.month-1]) + end_time.day + 1
        return list(range(start_doy, end_doy))
13398
def from_array(cls, array, sids):
        
        n_sites = len(sids)
        n = len(array)
        if n_sites != n:
            raise ValueError('Passed %d site IDs, but the array has length %d'
                             % (n_sites, n))
        if len(array.shape) == 2:  # shape (N, L) -> (N, L, 1)
            array = array.reshape(array.shape + (1,))
        self = cls(*array.shape[1:])
        for sid, poes in zip(sids, array):
            self[sid] = ProbabilityCurve(poes)
        return self
449042
def QA_util_get_trade_gap(start, end):
    ''
    start, end = QA_util_get_real_datelist(start, end)
    if start is not None:
        return trade_date_sse.index(end) + 1 - trade_date_sse.index(start)
    else:
        return 0
442184
def run(self):
        
        # 如果出现了日期的改变 才会进行结算的事件
        _date = None

        while QA_util_if_tradetime(self.now):
            for data in self.ingest_data:  # 对于在ingest_data中的数据
                # <class 'QUANTAXIS.QAData.QADataStruct.QA_DataStruct_Stock_day'>
                date = data.date[0]
                if self.market_type is MARKET_TYPE.STOCK_CN:  # 如果是股票市场
                    if _date != date:  # 如果新的date
                        # 前一天的交易日已经过去
                        # 往 broker 和 account 发送 settle 事件
                        try:
                            self.market.trade_engine.join()
                            # time.sleep(2)
                            self.market._settle(self.broker_name)

                        except Exception as e:
                            raise e
                # 基金 指数 期货
                elif self.market_type in [MARKET_TYPE.FUND_CN, MARKET_TYPE.INDEX_CN, MARKET_TYPE.FUTURE_CN]:
                    self.market._settle(self.broker_name)
                # print(data)
                self.broker.run(
                    QA_Event(event_type=ENGINE_EVENT.UPCOMING_DATA, market_data=data))
                # 生成 UPCOMING_DATA 事件放到 队列中去执行

                self.market.upcoming_data(self.broker_name, data)

                self.market.trade_engine.join()

                _date = date
1156759
public static Trades adaptTrades(WexTrade[] bTCETrades, CurrencyPair currencyPair) {

    List<Trade> tradesList = new ArrayList<>();
    long lastTradeId = 0;
    for (WexTrade bTCETrade : bTCETrades) {
      // Date is reversed order. Insert at index 0 instead of appending
      long tradeId = bTCETrade.getTid();
      if (tradeId > lastTradeId) {
        lastTradeId = tradeId;
      }
      tradesList.add(0, adaptTrade(bTCETrade, currencyPair));
    }
    return new Trades(tradesList, lastTradeId, TradeSortType.SortByID);
  }