Created
June 8, 2014 23:33
-
-
Save eddyb/6c6acd7e6f5738dbd333 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #![crate_id = ""] | |
| #![deny(missing_doc)] | |
| #![feature(macro_rules)] | |
| //! Documentation goes here. | |
| extern crate openssl; | |
| extern crate serialize; | |
| use std::io; | |
| use std::io::BufferedStream; | |
| use std::io::net::tcp::TcpStream; | |
| use serialize::{json, Decodable, Decoder, Encodable, Encoder}; | |
| use openssl::ssl::{Sslv23, SslContext, SslStream}; | |
| #[deriving(Show)] | |
| struct Time { | |
| pub ms: u64 | |
| } | |
| impl<Error, D: Decoder<Error>> Decodable<D, Error> for Time { | |
| fn decode(d: &mut D) -> Result<Time, Error> { | |
| Ok(Time { | |
| ms: try!(Decodable::decode(d)) | |
| }) | |
| } | |
| } | |
| impl<Error, E: Encoder<Error>> Encodable<E, Error> for Time { | |
| fn encode(&self, e: &mut E) -> Result<(), Error> { | |
| self.ms.encode(e) | |
| } | |
| } | |
| macro_rules! try_str ( | |
| ($e:expr) => (match $e { | |
| Ok(x) => x, | |
| Err(e) => return Err(e.to_str()) | |
| }) | |
| ) | |
| fn parse_response<R: Decodable<json::Decoder, json::DecoderError>>(mut d: json::Decoder) -> Result<R, String> { | |
| try_str!(d.read_struct("Response", 2, |d| { | |
| if try!(d.read_struct_field("status", 0, Decodable::decode)) { | |
| Ok(Ok(try!(d.read_struct_field("returnData", 1, Decodable::decode)))) | |
| } else { | |
| Ok(Err(try!(d.read_struct_field("errorDescr", 1, Decodable::decode)))) | |
| } | |
| })) | |
| } | |
| macro_rules! ident_or_str ( | |
| ($rname:ident) => (stringify!($rname)); | |
| ($rname:ident $name:expr) => ($name) | |
| ) | |
| macro_rules! req_encodable_sub_field ( | |
| () => (self.encode(e)); | |
| ($sub_field:expr) => ({ | |
| e.emit_struct("Info", 1, |e| e.emit_struct_field($sub_field, 0, |e| self.encode(e))) | |
| }) | |
| ) | |
| macro_rules! req_encodable ( | |
| ($name:expr $rname:ident $(.$sub_field:expr:)* { | |
| $($field_rname:ident $(@ $field_name:expr)*: $field_ty:ty),+ | |
| }) => { | |
| struct $rname { | |
| $($field_rname: $field_ty),* | |
| } | |
| impl<'a> Encodable<json::Encoder<'a>, io::IoError> for $rname { | |
| fn encode(&self, e: &mut json::Encoder<'a>) -> io::IoResult<()> { | |
| e.emit_struct(stringify!($rname), [$(stringify!($field_rname)),*].len(), |e| { | |
| let mut n = 0; | |
| $(try!(e.emit_struct_field(ident_or_str!($field_rname $($field_name)*), n, |e| self.$field_rname.encode(e))); n += 1;)* | |
| Ok(()) | |
| }) | |
| } | |
| } | |
| impl $rname { | |
| fn req_encode(&self, e: &mut json::Encoder) -> io::IoResult<()> { | |
| e.emit_struct("Request", 2, |e| { | |
| try!(e.emit_struct_field("command", 0, |e| $name.encode(e))); | |
| e.emit_struct_field("arguments", 1, |e| req_encodable_sub_field!($($sub_field)*)) | |
| }) | |
| } | |
| } | |
| }; | |
| ($name:expr $rname:ident) => { | |
| struct $rname; | |
| impl $rname { | |
| fn req_encode(&self, e: &mut json::Encoder) -> io::IoResult<()> { | |
| e.emit_struct("Request", 1, |e| e.emit_struct_field("command", 0, |e| $name.encode(e))) | |
| } | |
| } | |
| }; | |
| ) | |
| macro_rules! requests ( | |
| ($($name:expr $rname:ident $($(.$sub_field:expr:)* { | |
| $($field_rname:ident $(@ $field_name:expr)*: $field_ty:ty),+ | |
| })* $(-> $res_ty:ty $(, $dec_rname:ident { | |
| $($dec_field_rname:ident $(@ $dec_field_name:expr)*: $dec_field_ty:ty),+ | |
| })*)*;)*) => {$( | |
| req_encodable!($name $rname $($(.$sub_field:)* { | |
| $($field_rname $(@ $field_name)*: $field_ty),* | |
| })*) | |
| $(impl $rname { | |
| pub fn send(self, conn: &mut Connection) -> Result<$res_ty, String> { | |
| parse_response(try!(conn.send_request(|e| self.req_encode(e)))) | |
| } | |
| } $( | |
| #[deriving(Show)] | |
| struct $dec_rname { | |
| $($dec_field_rname: $dec_field_ty),* | |
| } | |
| impl Decodable<json::Decoder, json::DecoderError> for $dec_rname { | |
| fn decode(d: &mut json::Decoder) -> Result<$dec_rname, json::DecoderError> { | |
| d.read_struct(stringify!($dec_rname), [$(stringify!($dec_field_rname)),*].len(), |d| { | |
| let mut n = 0; | |
| Ok($dec_rname { | |
| $($dec_field_rname: { | |
| let v = try!(d.read_struct_field(ident_or_str!($dec_field_rname $($dec_field_name)*), n, Decodable::decode)); | |
| n += 1; | |
| v | |
| }),* | |
| }) | |
| }) | |
| } | |
| } | |
| )*)* | |
| )*} | |
| ) | |
| requests!{ | |
| "login" Login { | |
| user_id @ "userId": u64, | |
| password: String | |
| }; | |
| "logout" Logout; | |
| "getAllSymbols" GetAllSymbols -> Vec<Symbol>, Symbol { | |
| ask: f64, | |
| bid: f64, | |
| category_name @ "categoryName": String, | |
| contract_size @ "contractSize": u64, | |
| currency: String, | |
| currency_pair @ "currencyPair": bool, | |
| currency_profit @ "currencyProfit": String, | |
| description: String, | |
| expiration: Option<Time>, | |
| group_name @ "groupName": String, | |
| high: f64, | |
| initial_margin @ "initialMargin": u64, | |
| instant_max_volume @ "instantMaxVolume": u64, | |
| leverage: u64, | |
| long_only @ "longOnly": bool, | |
| lot_max @ "lotMax": f64, | |
| lot_min @ "lotMin": f64, | |
| lot_step @ "lotStep": f64, | |
| low: f64, | |
| margin_hedged @ "marginHedged": u64, | |
| margin_hedged_strong @ "marginHedgedStrong": bool, | |
| margin_maintenance @ "marginMaintenance": Option<u64>, | |
| margin_mode @ "marginMode": u8, // Forex=101, CFD_leveraged=102, CFD=103 | |
| percentage: f64, | |
| precision: u64, | |
| profit_mode @ "profitMode": u8, // FOREX=5, CFD=6 | |
| quote_id @ "quoteId": u8, // fixed=1, float=2, depth=3, cross=4 | |
| spread_raw @ "spreadRaw": f64, | |
| spread_table @ "spreadTable": f64, | |
| starting: Option<Time>, | |
| stops_level @ "stopsLevel": u64, | |
| swap_rollover3days: u64, | |
| swap_enable @ "swapEnable": bool, | |
| swap_long @ "swapLong": f64, | |
| swap_short @ "swapShort": f64, | |
| swap_type @ "swapType": u64, | |
| symbol: String, | |
| tick_size @ "tickSize": f64, | |
| tick_value @ "tickValue": f64, | |
| time: Time, | |
| type_ @ "type": u64 | |
| }; | |
| "getCalendar" GetCalendar -> Vec<CalendarRecord>, CalendarRecord { | |
| country: String, | |
| current: String, | |
| forecast: String, | |
| impact: String, | |
| period: String, | |
| previous: String, | |
| time: Time, | |
| title: String | |
| }; | |
| "getChartLastRequest" GetChartLastRequest ."info": { | |
| period: u64, // M1, M5, M15, M30, H1, H4, D1, W1, MN1 (30d) - in minutes | |
| start: Time, | |
| symbol: String | |
| } -> ChartResponse, ChartResponse { | |
| digits: u8, | |
| rate_infos @ "rateInfos": Vec<RateInfo> | |
| }, RateInfo { | |
| close: f64, | |
| ctm: Time, | |
| high: f64, | |
| low: f64, | |
| open: f64, | |
| vol: f64 | |
| }; | |
| "getChartRangeRequest" GetChartRangeRequest ."info": { | |
| end: Time, | |
| period: u64, // M1, M5, M15, M30, H1, H4, D1, W1, MN1 (30d) - in minutes | |
| start: Time, | |
| symbol: String, | |
| ticks: i64 | |
| } -> ChartResponse; | |
| "getCommissionDef" GetCommissionDef { | |
| symbol: String, | |
| volume: f64 | |
| } -> CommissionDef, CommissionDef { | |
| commision: f64, | |
| rate_of_exchange @ "rateOfExchange": f64 | |
| }; | |
| "getCurrentUserData" GetCurrentUserData -> UserData, UserData { | |
| company_unit @ "companyUnit": u64, | |
| currency: String, | |
| group: String, | |
| ib_account @ "ibAccount": bool, | |
| leverage_multiplier @ "leverageMultiplier": f64, | |
| spread_type @ "spreadType": String | |
| }; | |
| "getIbsHistory" GetIbsHistory { | |
| end: Time, | |
| start: Time | |
| } -> Vec<IbRecord>, IbRecord { | |
| close_price @ "closePrice": f64, | |
| login: String, | |
| nominal: f64, | |
| open_price @ "openPrice": f64, | |
| side: u8, // BUY=0, SELL=1 | |
| surname: String, | |
| symbol: String, | |
| timestamp: Time, | |
| volume: f64 | |
| }; | |
| "getMarginLevel" GetMarginLevel -> MarginLevel, MarginLevel { | |
| balance: f64, | |
| credit: f64, | |
| currency: String, | |
| equity: f64, | |
| margin: f64, | |
| margin_free: f64, | |
| margin_level: f64 | |
| }; | |
| "getMarginTrade" GetMarginTrade { | |
| symbol: String, | |
| volume: f64 | |
| } -> Margin, Margin { | |
| margin: f64 | |
| }; | |
| "getNews" GetNews { | |
| end: Time, | |
| start: Time | |
| } -> Vec<NewsTopic>, NewsTopic { | |
| body: String, | |
| key: String, | |
| time: Time, | |
| title: String | |
| }; | |
| "getProfitCalculation" GetProfitCalculation { | |
| close_price @ "closePrice": f64, | |
| cmd: u8, // BUY=0, SELL=1, BUY_LIMIT=2, SELL_LIMIT=3, BUY_STOP=4, SELL_STOP=5, BALANCE=6, CREDIT=7 | |
| open_price @ "openPrice": f64, | |
| symbol: String, | |
| volume: f64 | |
| } -> Profit, Profit { | |
| profit: f64 | |
| }; | |
| "getServerTime" GetServerTime -> ServerTime, ServerTime { | |
| time: Time | |
| }; | |
| "getStepRules" GetStepRules -> Vec<StepRule>, StepRule { | |
| id: u64, | |
| name: String, | |
| steps: Vec<Step> | |
| }, Step { | |
| from_value @ "fromValue": f64, | |
| step: f64 | |
| }; | |
| "getSymbol" GetSymbol { | |
| symbol: String | |
| } -> Symbol; | |
| "getTickPrices" GetTickPrices { | |
| level: i64, | |
| symbols: Vec<String>, | |
| timestamp: Time | |
| } -> TickPrices, TickPrices { | |
| quotations: Vec<TickPrice> | |
| }, TickPrice { | |
| ask: f64, | |
| ask_volume @ "askVolume": u64, | |
| bid: f64, | |
| bid_volume @ "bidVolume": u64, | |
| high: f64, | |
| level: i64, | |
| low: f64, | |
| spread_raw @ "spreadRaw": f64, | |
| spread_table @ "spreadTable": f64, | |
| symbol: String, | |
| timestamp: Time | |
| }; | |
| "getTradeRecords" GetTradeRecords { | |
| orders: Vec<u64> | |
| } -> Vec<Trade>, Trade { | |
| close_price: f64, | |
| close_time: Option<Time>, | |
| closed: bool, | |
| cmd: u8, // BUY=0, SELL=1, BUY_LIMIT=2, SELL_LIMIT=3, BUY_STOP=4, SELL_STOP=5, BALANCE=6, CREDIT=7 | |
| comment: String, | |
| commission: f64, | |
| custom_comment @ "customComment": String, | |
| digits: u8, | |
| expiration: Option<Time>, | |
| margin_rate: f64, | |
| open_price: f64, | |
| open_time: Time, | |
| order: u64, | |
| order2: u64, | |
| position: u64, | |
| profit: f64, | |
| sl: f64, | |
| storage: f64, | |
| symbol: String, | |
| timestamp: Time, | |
| tp: f64, | |
| volume: f64 | |
| }; | |
| "getTrades" GetTrades { | |
| opened_only @ "openedOnly": bool | |
| } -> Vec<Trade>; | |
| "getTradesHistory" GetTradesHistory { | |
| end: Time, | |
| start: Time | |
| } -> Vec<Trade>; | |
| "getTradingHours" GetTradingHours { | |
| symbols: Vec<String> | |
| } -> Vec<TradingHours>, TradingHours { | |
| quotes: Vec<WeekdayHours>, | |
| symbol: String, | |
| trading: Vec<WeekdayHours> | |
| }, WeekdayHours { | |
| day: u8, // 1-7 Monday-Sunday | |
| from @ "fromT": Time, | |
| to @ "toT": Time | |
| }; | |
| "getVersion" GetVersion -> Version, Version { | |
| version: String | |
| }; | |
| "ping" Ping; | |
| "tradeTransaction" TradeTransaction ."tradeTransInfo": { | |
| cmd: u8, // BUY=0, SELL=1, BUY_LIMIT=2, SELL_LIMIT=3, BUY_STOP=4, SELL_STOP=5, BALANCE=6, CREDIT=7 | |
| custom_comment @ "customComment": String, | |
| expiration: Time, | |
| order: u64, | |
| price: f64, | |
| sl: f64, | |
| symbol: String, | |
| tp: f64, | |
| type_ @ "type": u8, // OPEN=0, PENDING=1, CLOSE=2, MODIFY=3, DELETE=4 | |
| volume: f64 | |
| } -> TradeOrder, TradeOrder { | |
| order: u64 | |
| }; | |
| "tradeTransactionStatus" TradeTransactionStatus { | |
| order: u64 | |
| } -> TradeStatus, TradeStatus { | |
| ask: f64, | |
| bid: f64, | |
| custom_comment @ "customComment": String, | |
| message: Option<String>, | |
| order: u64, | |
| request_status @ "requestStatus": u8 // ERROR=0, PENDING=1, ACCEPTED=3, REJECTED=4 | |
| }; | |
| } | |
| struct LoginResponse { | |
| stream_session_id: String | |
| } | |
| impl Login { | |
| pub fn send(self, conn: &mut Connection) -> Result<LoginResponse, String> { | |
| let mut d = try!(conn.send_request(|e| self.req_encode(e))); | |
| try_str!(d.read_struct("LoginResponse", 2, |d| { | |
| if try!(d.read_struct_field("status", 0, Decodable::decode)) { | |
| Ok(Ok(LoginResponse { | |
| stream_session_id: try!(d.read_struct_field("streamSessionId", 1, Decodable::decode)) | |
| })) | |
| } else { | |
| Ok(Err(try!(d.read_struct_field("errorDescr", 1, Decodable::decode)))) | |
| } | |
| })) | |
| } | |
| } | |
| struct Connection { | |
| stream: BufferedStream<SslStream<TcpStream>>, | |
| stream_session_id: String | |
| } | |
| impl Connection { | |
| fn new(server: &str, port: u16, user_id: u64, password: &str) -> Result<Connection, String> { | |
| let stream = try_str!(TcpStream::connect(server, port)); | |
| let stream = SslStream::new(&SslContext::new(Sslv23), stream); | |
| let mut conn = Connection { | |
| stream: BufferedStream::new(stream), | |
| stream_session_id: String::new() | |
| }; | |
| conn.stream_session_id = try!(Login { | |
| user_id: user_id, | |
| password: password.to_string() | |
| }.send(&mut conn)).stream_session_id; | |
| Ok(conn) | |
| } | |
| fn send_request(&mut self, encode: |&mut json::Encoder| -> io::IoResult<()>) -> Result<json::Decoder, String> { | |
| try_str!(encode(&mut json::Encoder::new(&mut self.stream))); | |
| try_str!(self.stream.flush()) | |
| let response = try_str!(self.stream.read_line()); | |
| let second_line = try_str!(self.stream.read_line()); | |
| if second_line.as_slice() != "\n" { | |
| return Err(format!("expected empty line after response, got `{}`", second_line)); | |
| } | |
| Ok(json::Decoder::new(try_str!(json::from_str(response.as_slice())))) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment