Places a margin sell order in a given market. Parameters and output
        are the same as for the marginBuy method.
333591
def marginSell(self, currencyPair, rate, amount, lendingRate=None):
        """"""
        return self._private('marginSell', currencyPair=currencyPair, rate=rate,
                             amount=amount, lendingRate=lendingRate)
52377
function (bid) {
    return !!(bid && bid.params && (bid.params.placementId || (bid.params.placementKey && bid.params.publisherId)));
  }
485407
public function createSell(Sell $sell, array $params = [])
    {
        $this->getClient()->createAccountSell($this, $sell, $params);
    }
114863
def on_bar(self, event):
        '''
        
        '''
        'while updating the market data'

        print(
            "on_bar account {} ".format(self.account_cookie),
            event.market_data.data
        )
        print(event.send_order)
        try:
            for code in event.market_data.code:

                if self.sell_available.get(code, 0) > 0:
                    print('可以卖出 {}'.format(self._currenttime))
                    event.send_order(
                        account_cookie=self.account_cookie,
                        amount=self.sell_available[code],
                        amount_model=AMOUNT_MODEL.BY_AMOUNT,
                        time=self.current_time,
                        code=code,
                        price=0,
                        order_model=ORDER_MODEL.MARKET,
                        towards=ORDER_DIRECTION.SELL,
                        market_type=self.market_type,
                        frequence=self.frequence,
                        broker_name=self.broker
                    )
                else:
                    print('{} 无仓位, 买入{}'.format(self._currenttime, code))
                    event.send_order(
                        account_cookie=self.account_cookie,
                        amount=100,
                        amount_model=AMOUNT_MODEL.BY_AMOUNT,
                        time=self.current_time,
                        code=code,
                        price=0,
                        order_model=ORDER_MODEL.MARKET,
                        towards=ORDER_DIRECTION.BUY,
                        market_type=self.market_type,
                        frequence=self.frequence,
                        broker_name=self.broker
                    )
        except Exception as e:
            print(e)
676824
def sell(self, security, price=0, amount=0, volume=0, entrust_prop=0):
        
        return self._trade(security, price, amount, volume, "sell")
1201739
def _register_trade(self, order):
        
        if order['id'] in self.orders.recent:
            orderId = order['id']
        else:
            orderId = order['parentId']
        # entry / exit?
        symbol = order["symbol"]
        order_data = self.orders.recent[orderId]
        position = self.get_positions(symbol)['position']

        if position != 0:
            # entry
            order_data['action'] = "ENTRY"
            order_data['position'] = position
            order_data['entry_time'] = tools.datetime_to_timezone(
                order['time'])
            order_data['exit_time'] = None
            order_data['entry_order'] = order_data['order_type']
            order_data['entry_price'] = order['avgFillPrice']
            order_data['exit_price'] = 0
            order_data['exit_reason'] = None

        else:
            order_data['action'] = "EXIT"
            order_data['position'] = 0
            order_data['exit_time'] = tools.datetime_to_timezone(order['time'])
            order_data['exit_price'] = order['avgFillPrice']

            # target / stop?
            if order['id'] == order_data['targetOrderId']:
                order_data['exit_reason'] = "TARGET"
            elif order['id'] == order_data['stopOrderId']:
                order_data['exit_reason'] = "STOP"
            else:
                order_data['exit_reason'] = "SIGNAL"

            # remove from collection
            del self.orders.recent[orderId]

        if order_data is None:
            return None

        # trade identifier
        tradeId = self.strategy.upper() + '_' + symbol.upper()
        tradeId = hashlib.sha1(tradeId.encode()).hexdigest()

        # existing trade?
        if tradeId not in self.active_trades:
            self.active_trades[tradeId] = {
                "strategy": self.strategy,
                "action": order_data['action'],
                "quantity": abs(order_data['position']),
                "position": order_data['position'],
                "symbol": order_data["symbol"].split('_')[0],
                "direction": order_data['direction'],
                "entry_time": None,
                "exit_time": None,
                "duration": "0s",
                "exit_reason": order_data['exit_reason'],
                "order_type": order_data['order_type'],
                "market_price": order_data['price'],
                "target": order_data['target'],
                "stop": order_data['initial_stop'],
                "entry_price": 0,
                "exit_price": order_data['exit_price'],
                "realized_pnl": 0
            }
            if "entry_time" in order_data:
                self.active_trades[tradeId]["entry_time"] = order_data['entry_time']
            if "entry_price" in order_data:
                self.active_trades[tradeId]["entry_price"] = order_data['entry_price']
        else:
            # self.active_trades[tradeId]['direction']   = order_data['direction']
            self.active_trades[tradeId]['action'] = order_data['action']
            self.active_trades[tradeId]['position'] = order_data['position']
            self.active_trades[tradeId]['exit_price'] = order_data['exit_price']
            self.active_trades[tradeId]['exit_reason'] = order_data['exit_reason']
            self.active_trades[tradeId]['exit_time'] = order_data['exit_time']

            # calculate trade duration
            try:
                delta = int((self.active_trades[tradeId]['exit_time'] -
                             self.active_trades[tradeId]['entry_time']).total_seconds())
                days, remainder = divmod(delta, 86400)
                hours, remainder = divmod(remainder, 3600)
                minutes, seconds = divmod(remainder, 60)
                duration = ('%sd %sh %sm %ss' %
                            (days, hours, minutes, seconds))
                self.active_trades[tradeId]['duration'] = duration.replace(
                    "0d ", "").replace("0h ", "").replace("0m ", "")
            except Exception as e:
                pass

            trade = self.active_trades[tradeId]
            if trade['entry_price'] > 0 and trade['position'] == 0:
                if trade['direction'] == "SELL":
                    pnl = trade['entry_price'] - trade['exit_price']
                else:
                    pnl = trade['exit_price'] - trade['entry_price']

                pnl = tools.to_decimal(pnl)
                # print("1)", pnl)
                self.active_trades[tradeId]['realized_pnl'] = pnl

        # print("\n\n-----------------")
        # print(self.active_trades[tradeId])
        # print("-----------------\n\n")

        # get trade
        trade = self.active_trades[tradeId].copy()

        # sms trades
        sms._send_trade(trade, self.sms_numbers, self.timezone)

        # rename trade direction
        trade['direction'] = trade['direction'].replace(
            "BUY", "LONG").replace("SELL", "SHORT")

        # log
        self.log_trade(trade)

        # remove from active trades and add to trade
        if trade['action'] == "EXIT":
            del self.active_trades[tradeId]
            self.trades.append(trade)

        # return trade
        return trade
1094037
def _calculate_price_by_slippage(self, action: str, price: float) -> float:
        
        if action == "buy":
            return price * (1 + self.slippage)
        if action == "sell":
            return price * (1 - self.slippage)
        return price
1264787
function parseAccountOrder(address: string, order: Object): Object {
  const direction = (order.flags & flags.Sell) === 0 ? 'buy' : 'sell'
  const takerGetsAmount = parseAmount(order.taker_gets)
  const takerPaysAmount = parseAmount(order.taker_pays)
  const quantity = (direction === 'buy') ? takerPaysAmount : takerGetsAmount
  const totalPrice = (direction === 'buy') ? takerGetsAmount : takerPaysAmount

  // note: immediateOrCancel and fillOrKill orders cannot enter the order book
  // so we can omit those flags here
  const specification = utils.removeUndefined({
    direction: direction,
    quantity: quantity,
    totalPrice: totalPrice,
    passive: ((order.flags & flags.Passive) !== 0) || undefined,
    // rippled currently does not provide "expiration" in account_offers
    expirationTime: utils.parseTimestamp(order.expiration)
  })

  const makerExchangeRate = order.quality ?
      utils.adjustQualityForZXC(order.quality.toString(),
        takerGetsAmount.currency, takerPaysAmount.currency) :
      computeQuality(takerGetsAmount, takerPaysAmount)
  const properties = {
    maker: address,
    sequence: order.seq,
    makerExchangeRate: makerExchangeRate
  }

  return {specification, properties}
}
468437
def place_limit_order(self, side: Side, amount: Number, price: Number) -> Order:
        """"""
        return self.place_order(side, OrderType.LIMIT, amount, price)
236999
def create_order(order):
    
    SaleOrder = client.model('sale.sale')
    SaleOrderLine = client.model('sale.line')

    # Check if customer exists, if not create one
    customer_id = get_customer(order['customer']['code'])
    if not customer_id:
        customer_id = create_customer(
            order['customer']['name'],
            order['customer']['email'],
            order['customer']['phone'],
        )

    # No check if there is a matching address
    invoice_address = get_address(
        customer_id,
        order['invoice_address']
    )
    if not invoice_address:
        invoice_address = create_address(
            customer_id,
            order['invoice_address']
        )

    # See if the shipping address exists, if not create it
    shipment_address = get_address(
        customer_id,
        order['shipment_address']
    )
    if not shipment_address:
        shipment_address = create_address(
            customer_id,
            order['shipment_address']
        )

    sale_order_id, = SaleOrder.create([{
        'reference': order['number'],
        'sale_date': order['date'],
        'party': customer_id,
        'invoice_address': invoice_address,
        'shipment_address': shipment_address,
    }])

    # fetch inventory of all the products before we create lines
    warehouses = get_warehouses()
    warehouse_ids = [warehouse['id'] for warehouse in warehouses]

    lines = []
    for item in order['items']:
        # get the product. We assume ti already exists.
        product = get_product(item['product'])

        # find the first location that has inventory
        product_inventory = get_product_inventory(product, warehouse_ids)
        for location, quantities in product_inventory.items():
            if quantities['quantity_available'] >= item['quantity']:
                break

        lines.append({
            'sale': sale_order_id,
            'product': product,
            'quantity': item['quantity'],
            'unit_price': item['unit_price'],
            'warehouse': location,
        })

    SaleOrderLine.create(lines)

    SaleOrder.quote([sale_order_id])
    SaleOrder.confirm([sale_order_id])
142203
def buy_limit_order(self, amount, price, base="btc", quote="usd", limit_price=None):
        
        data = {'amount': amount, 'price': price}
        if limit_price is not None:
            data['limit_price'] = limit_price
        url = self._construct_url("buy/", base, quote)
        return self._post(url, data=data, return_json=True, version=2)
893057
public static BitfinexOrderBookSymbol orderBook(final BitfinexCurrencyPair currencyPair, 
    		final BitfinexOrderBookSymbol.Precision precision,
    		final BitfinexOrderBookSymbol.Frequency frequency, final int pricePoints) {
    	
        if (precision == BitfinexOrderBookSymbol.Precision.R0) {
            throw new IllegalArgumentException("Use BitfinexSymbols#rawOrderBook() factory method instead");
        }
        
        return new BitfinexOrderBookSymbol(currencyPair, precision, frequency, pricePoints);
    }
642857
def set_bottom_margin(self, bottom_margin):
        
        self.__footer.style.margins.bottom = bottom_margin
        return self
907845
def addMov(self, product, quantity=None, mode="buy", stop_limit=None,
               auto_margin=None, name_counter=None):
        """"""
        # ~ ARGS ~
        if (not isinstance(product, type('')) or
                (not isinstance(name_counter, type('')) and
                 name_counter is not None)):
            raise ValueError('product and name_counter have to be a string')
        if not isinstance(stop_limit, type({})) and stop_limit is not None:
            raise ValueError('it has to be a dictionary')
        # exclusive args
        if quantity is not None and auto_margin is not None:
            raise ValueError("quantity and auto_margin are exclusive")
        elif quantity is None and auto_margin is None:
            raise ValueError("need at least one quantity")
        # ~ MAIN ~
        # open new window
        mov = self.new_mov(product)
        mov.open()
        mov.set_mode(mode)
        # set quantity
        if quantity is not None:
            mov.set_quantity(quantity)
            # for best performance in long times
            try:
                margin = mov.get_unit_value() * quantity
            except TimeoutError:
                mov.close()
                logger.warning("market closed for %s" % mov.product)
                return False
        # auto_margin calculate quantity (how simple!)
        elif auto_margin is not None:
            unit_value = mov.get_unit_value()
            mov.set_quantity(auto_margin * unit_value)
            margin = auto_margin
        # stop limit (how can be so simple!)
        if stop_limit is not None:
            mov.set_limit('gain', stop_limit['gain'][0], stop_limit['gain'][1])
            mov.set_limit('loss', stop_limit['loss'][0], stop_limit['loss'][1])
        # confirm
        try:
            mov.confirm()
        except (exceptions.MaxQuantLimit, exceptions.MinQuantLimit) as e:
            logger.warning(e.err)
            # resolve immediately
            mov.set_quantity(e.quant)
            mov.confirm()
        except Exception:
            logger.exception('undefined error in movement confirmation')
        mov_logger.info(f"added {mov.product} movement of {mov.quantity} " +
                        f"with margin of {margin}")
        mov_logger.debug(f"stop_limit: {stop_limit}")
1247361
def __placeStopOrder(self, order):
        '''  '''
        orderId=self.__strategy.placeOrder(order)
        if orderId:
            self.__stopOrderId=orderId
            self.__stopOrder=order
        else:
            LOG.error("Can't  %s" % order)
22036
def __convert_order_params_for_blotter(asset,
                                           limit_price,
                                           stop_price,
                                           style):
        
        if style:
            assert (limit_price, stop_price) == (None, None)
            return style
        if limit_price and stop_price:
            return StopLimitOrder(limit_price, stop_price, asset=asset)
        if limit_price:
            return LimitOrder(limit_price, asset=asset)
        if stop_price:
            return StopOrder(stop_price, asset=asset)
        else:
            return MarketOrder()
670482
def validate_order_params(self,
                              asset,
                              amount,
                              limit_price,
                              stop_price,
                              style):
        

        if not self.initialized:
            raise OrderDuringInitialize(
                msg="order() can only be called from within handle_data()"
            )

        if style:
            if limit_price:
                raise UnsupportedOrderParameters(
                    msg="Passing both limit_price and style is not supported."
                )

            if stop_price:
                raise UnsupportedOrderParameters(
                    msg="Passing both stop_price and style is not supported."
                )

        for control in self.trading_controls:
            control.validate(asset,
                             amount,
                             self.portfolio,
                             self.get_datetime(),
                             self.trading_client.current_data)