Skip to content

Commit

Permalink
Add support for negating "sides"
Browse files Browse the repository at this point in the history
The Side enum we use for capturing which side an order or position is on
has exactly two values with "opposing" meaning. Client code may
reasonably want to negate a side and expect the result to be the other
one.
This change enables such use cases by implementing the Not trait for
both types.
  • Loading branch information
d-e-s-o committed Mar 9, 2020
1 parent 9df9201 commit 2a8ce0c
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
Unreleased
----------
- Added support for negating order and position `Side` types


0.8.0
-----
- Added support for associating client IDs with orders
Expand Down
18 changes: 18 additions & 0 deletions src/api/v2/order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// SPDX-License-Identifier: GPL-3.0-or-later

use std::ops::Deref;
use std::ops::Not;
use std::time::SystemTime;

use hyper::Body;
Expand Down Expand Up @@ -122,6 +123,17 @@ pub enum Side {
Sell,
}

impl Not for Side {
type Output = Self;

fn not(self) -> Self::Output {
match self {
Self::Buy => Self::Sell,
Self::Sell => Self::Buy,
}
}
}


/// The type of an order.
// Note that we currently do not support `stop_limit` orders.
Expand Down Expand Up @@ -508,6 +520,12 @@ mod tests {
assert_eq!(to_json(&Side::Sell).unwrap(), r#""sell""#);
}

#[test]
fn negate_side() {
assert_eq!(!Side::Buy, Side::Sell);
assert_eq!(!Side::Sell, Side::Buy);
}

#[test]
fn emit_type() {
assert_eq!(to_json(&Type::Market).unwrap(), r#""market""#);
Expand Down
19 changes: 19 additions & 0 deletions src/api/v2/position.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright (C) 2019-2020 Daniel Mueller <[email protected]>
// SPDX-License-Identifier: GPL-3.0-or-later

use std::ops::Not;

use hyper::Method;

use num_decimal::Num;
Expand All @@ -24,6 +26,17 @@ pub enum Side {
Short,
}

impl Not for Side {
type Output = Self;

fn not(self) -> Self::Output {
match self {
Self::Long => Self::Short,
Self::Short => Self::Long,
}
}
}


/// A single position as returned by the /v2/positions endpoint on a GET
/// request.
Expand Down Expand Up @@ -134,6 +147,12 @@ mod tests {
use crate::Client;


#[test]
fn negate_side() {
assert_eq!(!Side::Long, Side::Short);
assert_eq!(!Side::Short, Side::Long);
}

#[test]
fn parse_reference_position() {
let response = r#"{
Expand Down

0 comments on commit 2a8ce0c

Please sign in to comment.